package com.yantong.service.impl;

import com.github.pagehelper.util.StringUtil;
import com.yantong.enums.MarketingGroupTypeEnum;
import com.yantong.config.LocalRedis;
import com.yantong.constant.CacheKeyLocal;
import com.yantong.constant.MemberType;
import com.yantong.constant.ProductType;
import com.yantong.constant.StringConstans;
import com.yantong.exception.BDException;
import com.yantong.mapper.*;
import com.yantong.pojo.*;
import com.yantong.pojo.vo.*;
import com.yantong.service.*;
import com.yantong.utils.*;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.awt.image.BufferedImage;
import java.io.*;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Base64.Encoder;

import static com.yantong.constant.CacheKeyLocal.CACHE_KEY_PRODUCT_CENTRE_SALE;
import static com.yantong.constant.CacheKeyLocal.CACHE_KEY_PRODUCT_SALE;


/**
 * @author kanghaixin
 */
@Service
public class ProductCentreServiceImpl implements ProductCentreService {
	private static final Logger logger = LoggerFactory.getLogger(ProductCentreServiceImpl.class);
	private static final String CACHE_NAME = "CENTRE_PRODUCT_";
	private static final String CACHE_SKU_NAME = "CENTRE_SKU_";
	@Autowired
	private ProductCentreMapper pCentreMapper;
	@Autowired
	private MemberMapper memberMapper;
	@Autowired
	private ProductSpecMapper productSpecMapper;
	@Autowired
	private ProductDataSpecMapper productDataSpecMapper;
	@Autowired
	private ProductSkuCentreMapper productSkuCentreMapper;
	@Autowired
	private OrderProductMapper orderProductMapper;
	@Autowired
	private RecommendMapper recommendMapper;
	@Autowired
	private ProductDataMapper productDataMapper;
	@Autowired
	private ProductMapper productMapper;
	@Autowired
	private ProductSkuMapper skuMapper;
	@Autowired
	private ProductDataSkuMapper dataSkuMapper;
	@Autowired
	private MemberCartMapper memberCartMapper;
	@Autowired
	private OssService ossService;
	@Autowired
	private ProductSpecCentreMapper specCentreMapper;
	@Autowired
	private ProductSpecItemCentreMapper specItemCentreMapper;
	@Autowired
	private ProductSpecItemMapper specItemMapper;
	@Autowired
	private ProductDataSpecItemMapper dataSpecItemMapper;
	@Autowired
	private CentreService centreService;
	@Autowired
	private LocalRedis localRedis;
	@Autowired
	private StringRedisTemplate stringRedisTemplate;
	@Autowired
	private CategoryService categoryService;
	@Autowired
	private GoodsPicService goodsPicService;
	@Autowired
	private StringRedisTemplate redisTemplate;
	@Autowired
	@Lazy
	private ProductService productService;
	@Autowired
	private ProductDataService productDataService;
//	@Autowired
//	private CentreTokenService centreTokenService;
	@Autowired
	private MarketingGroupMapper marketingGroupMapper;
	//    private MarketingGroupService marketingGroupService;
	@Autowired
	private MarketingSeckillMapper marketingSeckillMapper;
	//    private MarketingSeckillService marketingSeckillService;
	@Autowired
	private ConfigService configService;
	@Autowired
	private ProductCentreMapper productCentreMapper;
	@Autowired
	private CategoryMapper categoryMapper;
	@Autowired
	private ProductPackageSkuMapper productPackageSkuMapper;


	@Override
	public PageUtils<ProductCentre> listCentreProducts(int offset, int limit, ProductsReqVo productsReqVo) {
		PageUtils<ProductCentre> pageUtils = new PageUtils<>();
		HashMap<String, Object> map = new HashMap<>(4);
		Member commander = null;
		//不是快递直发商品
        /*if(productsReqVo.getIsKuaidi()==null) {
	        Long teamId = productsReqVo.getTeamId();
	        if (teamId == null) {
	            logger.info("listCentreProducts lose teamId!!");
	            return pageUtils;
	        }
	        commander = memberMapper.selectByPrimaryKey(teamId);
	        if (commander == null) {
	            logger.info("not found commander by teamId:{}", teamId);
	            return pageUtils;
	        }
	        if (productsReqVo.getCentreId() == null) {
	            productsReqVo.setCentreId(commander.getCentreId());
	        }
		        map.put("centreId", productsReqVo.getCentreId());
		        map.put("teamId", "#" + productsReqVo.getTeamId() + "#");
		        map.put("teamArea", commander.gettCity());
        }else {
        	//是快递直发商品
        	map.put("isKuaidi", productsReqVo.getIsKuaidi());
        }*/
		Long teamId = productsReqVo.getTeamId();
		if (teamId == null) {
			logger.info("listCentreProducts lose teamId!!");
			return pageUtils;
		}
		commander = memberMapper.selectByPrimaryKey(teamId);
		if (commander == null) {
			logger.info("not found commander by teamId:{}", teamId);
			return pageUtils;
		}
		if (productsReqVo.getCentreId() == null) {
			productsReqVo.setCentreId(commander.getCentreId());
		}
		if (productsReqVo.getIsKuaidi() != null && productsReqVo.getIsKuaidi() == 1) {
			//是快递直发商品
			map.put("isKuaidi", productsReqVo.getIsKuaidi());
		}
		map.put("centreId", productsReqVo.getCentreId());
		map.put("teamId", "#" + productsReqVo.getTeamId() + "#");
		map.put("teamArea", commander.gettCity());
		if (productsReqVo.getIshot() != null) {
			map.put("ishot", productsReqVo.getIshot());
		}
		if (productsReqVo.getIsnew() != null) {
			map.put("isnew", productsReqVo.getIsnew());
		}
		if (productsReqVo.getIsmiaosha() != null) {
			map.put("ismiaosha", productsReqVo.getIsmiaosha());
		}
		if (productsReqVo.getIsvip() != null) {
			map.put("isvip", productsReqVo.getIsvip());
		}
		if (productsReqVo.getCategoryId() != null) {
			map.put("categoryId", productsReqVo.getCategoryId());
		}
		if (StringUtils.isNotEmpty(productsReqVo.getTitle())) {
			map.put("title", productsReqVo.getTitle());
		}
		if (productsReqVo.getLiansuoid() != null && productsReqVo.getLiansuoid() != 0) {
			map.put("liansuoid", productsReqVo.getLiansuoid());
		}
		if (productsReqVo.getIsSpellgroup() != null) {
			map.put("isSpellgroup", productsReqVo.getIsSpellgroup());
		}
		if (productsReqVo.getProductType() != null) {
			map.put("productType", productsReqVo.getProductType());
		}
		//预售
		if (productsReqVo.getIspresell() != null) {
			map.put("ispresell", productsReqVo.getIspresell());
		}
        /*if (productsReqVo.getIsSpellgroup()!=null) {
            map.put("isSpellgroup",productsReqVo.getIsSpellgroup());
        }*/
		if (commander != null) {
			if (commander.getIsteam() == 3 && productsReqVo.getIsTeam() != null) {
				map.put("isTeamBuy", 1);
			} else {
				map.put("isTeamBuy", 0);
			}
		}
		if (productsReqVo.getProductPackageFlag() != null) {
			map.put("productPackageFlag", productsReqVo.getProductPackageFlag());
		}
		GoodsPic goodsPic = null;
		if (productsReqVo.getIsKuaidi() == null) {
			//根据商户查询最近的主题图框
			goodsPic = goodsPicService.getIszhutihuakuang(productsReqVo.getCentreId());
		}
		int total = pCentreMapper.countCentre(map);
		if (total > 0) {
			pageUtils.setTotal(total);
			List<ProductCentre> list = pCentreMapper.listCentre(map, new RowBounds(offset, limit));
          /* //商品列表
            if(productsReqVo.getCategoryId()== null) {
            	//筛选掉活动专区的商品
            	list = list.stream().filter(ProductCentre ->  ProductCentre.getPcate().longValue()
            			!= 630716 &&  ProductCentre.getPcate().longValue()
            			!= 630759).collect(Collectors.toList());
            }*/
			for (ProductCentre pc : list) {
				if (productsReqVo.getIsKuaidi() != null) {
					//根据商户查询最近的主题图框
					goodsPic = goodsPicService.getIszhutihuakuang(pc.getCentreId());
				}
				//判断商品有没有勾选主题图框
				if (pc.getIszhutihuakuang() == 1 && goodsPic != null && goodsPic.getPic() != null) {
					pc.setZttkURL(goodsPic.getPic());
				}
				if (productsReqVo.getMid() != null) {
					String s = redisTemplate.opsForValue().get("cardTotal:" + productsReqVo.getMid() + ":" + pc.getId());
					String s1 = s == null ? "0" : s;
					pc.setCartNum(Integer.parseInt(s1));
				}

				String count = redisTemplate.opsForValue().get("PRODUCT_VIEW_COUNT_" + pc.getId());
				if (count != null) {
					pc.setViewcount(Integer.valueOf(count));
				}

				Long pid = pc.getProductId();
				if (pid != null && pid > 0) {
					Product product = productMapper.selectByPrimaryKey(pid);

					pc.setGrandtotal(product.getGrandtotal());
					Integer saleReal = 0;
					Object sale = stringRedisTemplate.opsForValue().get(CacheKeyLocal.CACHE_KEY_PRODUCT_SALE.concat(String.valueOf(product.getId())));
					if (sale == null) {
						saleReal = product.getSalesreal();
					} else {
						saleReal = (Integer) sale;
					}
					pc.setSalesreal(saleReal);
					pc.setTotal(product.getTotal());
				} else {
					Object sale = stringRedisTemplate.opsForValue().get(CACHE_KEY_PRODUCT_CENTRE_SALE.concat(pc.getId().toString()));
					if (sale != null) {
						pc.setSalesreal((Integer) sale);
					}
				}

				//查询商品规格
				if (pc.getHasoption() == 1) {
					pc.setSkus(productSkuCentreMapper.getByProductId(pc.getId()));
				}

			}
			pageUtils.setRows(list);
		}
		return pageUtils;
	}

	/**
	 * 商户商品列表 前端用
	 *
	 * @param offset
	 * @param limit
	 * @param productsReqVo
	 * @return
	 */
	@Override
	public PageUtils<ProductCentre> getListCentreProducts(int offset, int limit, ProductsReqVo productsReqVo) {
		PageUtils<ProductCentre> pageUtils = new PageUtils<>();
		HashMap<String, Object> map = new HashMap<>(4);
//        Member commander = null;

//        Long teamId = productsReqVo.getTeamId();
//        if (teamId == null) {
//            logger.info("listCentreProducts lose teamId!!");
//            return pageUtils;
//        }
//        commander = memberMapper.selectByPrimaryKey(teamId);
//        if (commander == null) {
//            logger.info("not found commander by teamId:{}", teamId);
//            return pageUtils;
//        }
//        if (productsReqVo.getCentreId() == null) {
//            productsReqVo.setCentreId(commander.getCentreId());
//        }
        /*if (productsReqVo.getIsKuaidi() != null && productsReqVo.getIsKuaidi() == 1) {
            //是快递直发商品
            map.put("isKuaidi", productsReqVo.getIsKuaidi());
        }*/
		map.put("isKuaidi", productsReqVo.getIsKuaidi());
		if (productsReqVo.getCentreId() != null) {
			map.put("centreId", productsReqVo.getCentreId());
		}
		//map.put("teamId", productsReqVo.getTeamId());
//        map.put("teamIdStr", "#" + productsReqVo.getTeamId() + "#");
//        map.put("teamArea", commander.gettCity());
		if (productsReqVo.getIshot() != null) {
			map.put("ishot", productsReqVo.getIshot());
		}
		if (productsReqVo.getIsnew() != null) {
			map.put("isnew", productsReqVo.getIsnew());
		}
		if (productsReqVo.getIsmiaosha() != null) {
			map.put("ismiaosha", productsReqVo.getIsmiaosha());
		}
		if (productsReqVo.getCentreFlag() != null) {
			map.put("centreFlag", productsReqVo.getCentreFlag());
		} else {
			map.put("centreFlag", true);
		}
		if (productsReqVo.getIsvip() != null) {
			map.put("isvip", productsReqVo.getIsvip());
		}
		if (productsReqVo.getIsmao() != null) {
			map.put("ismao", productsReqVo.getIsmao());
		}
		if (productsReqVo.getCategoryId() != null) {
			map.put("categoryId", productsReqVo.getCategoryId());
		}
		if (StringUtils.isNotEmpty(productsReqVo.getTitle())) {
			map.put("title", productsReqVo.getTitle());
		}
		if (productsReqVo.getTeamId() != null) {
			map.put("teamId", productsReqVo.getTeamId());
		}
		if (productsReqVo.getLiansuoid() != null && productsReqVo.getLiansuoid() != 0) {
			map.put("liansuoid", productsReqVo.getLiansuoid());
		}
		if (productsReqVo.getIsSpellgroup() != null) {
			map.put("isSpellgroup", productsReqVo.getIsSpellgroup());
		}
		if (productsReqVo.getProductType() != null) {
			map.put("productType", productsReqVo.getProductType());
		}
		//预售
		if (productsReqVo.getIspresell() != null) {
			map.put("ispresell", productsReqVo.getIspresell());
		}
		//状态
		if (productsReqVo.getStatus() != null) {
			map.put("status", productsReqVo.getStatus());
		}
		if (productsReqVo.getIsziti() != null) {
			map.put("isziti", productsReqVo.getIsziti());
		}
		if (productsReqVo.getIswaimai() != null) {
			map.put("iswaimai", productsReqVo.getIswaimai());
		}
		if (productsReqVo.getIstangshi() != null) {
			map.put("istangshi", productsReqVo.getIstangshi());
		}
		if (productsReqVo.getProductPackageFlag() != null) {
			map.put("productPackageFlag", productsReqVo.getProductPackageFlag());
		}
        /*if (productsReqVo.getIsSpellgroup()!=null) {
            map.put("isSpellgroup",productsReqVo.getIsSpellgroup());
        }*/
//        if (commander != null) {
//            if (commander.getIsteam() == 3 && productsReqVo.getIsTeam() != null) {
//                map.put("isTeamBuy", 1);
//            } else {
//                map.put("isTeamBuy", 0);
//            }
//        }
		//排序
		if (StringUtil.isNotEmpty(productsReqVo.getSidx())) {
			if (productsReqVo.getSidx().equals("marketprice")) {//价格排序
				map.put("sidx", "pc.marketprice");
				map.put("order", StringUtil.isNotEmpty(productsReqVo.getOrder()) ? productsReqVo.getOrder() : "desc");
			} else if (productsReqVo.getSidx().equals("salesreal")) {
				map.put("sidx", "pc.salesreal");
				map.put("order", StringUtil.isNotEmpty(productsReqVo.getOrder()) ? productsReqVo.getOrder() : "desc");
			} else if (productsReqVo.getSidx().equals("isnew")) {
				String sidx = "pc.isnew " + (StringUtil.isNotEmpty(productsReqVo.getOrder()) ? productsReqVo.getOrder() : "desc") + ", pc.createtime";
				map.put("sidx", sidx);
				map.put("order", StringUtil.isNotEmpty(productsReqVo.getOrder()) ? productsReqVo.getOrder() : "desc");
			}
		}
		//价格区间筛选
		if (productsReqVo.getMinPrice() != null && productsReqVo.getMinPrice().compareTo(BigDecimal.ZERO) == 1) {
			map.put("minPrice", productsReqVo.getMinPrice());
		}
		if (productsReqVo.getMaxPrice() != null && productsReqVo.getMaxPrice().compareTo(BigDecimal.ZERO) == 1) {
			map.put("maxPrice", productsReqVo.getMaxPrice());
		}
		//积分区间筛选
		if (productsReqVo.getMinScore() != null && productsReqVo.getMinScore().compareTo(BigDecimal.ZERO) == 1) {
			map.put("minScore", productsReqVo.getMinScore());
		}
		if (productsReqVo.getMaxScore() != null && productsReqVo.getMaxScore().compareTo(BigDecimal.ZERO) == 1) {
			map.put("maxScore", productsReqVo.getMaxScore());
		}

		GoodsPic goodsPic = null;
		if (productsReqVo.getIsKuaidi() == null) {
			//根据商户查询最近的主题图框
			goodsPic = goodsPicService.getIszhutihuakuang(productsReqVo.getCentreId());
		}
		int total = pCentreMapper.countCentre(map);
		if (total > 0) {
			pageUtils.setTotal(total);
			// List<ProductCentre> list = pCentreMapper.listCentre(map, new RowBounds(offset, limit));
			List<ProductCentre> list = pCentreMapper.getListCentreProducts(map, new RowBounds(offset, limit));
          /* //商品列表
            if(productsReqVo.getCategoryId()== null) {
            	//筛选掉活动专区的商品
            	list = list.stream().filter(ProductCentre ->  ProductCentre.getPcate().longValue()
            			!= 630716 &&  ProductCentre.getPcate().longValue()
            			!= 630759).collect(Collectors.toList());
            }*/
			for (ProductCentre pc : list) {
				if (productsReqVo.getIsKuaidi() != null) {
					//根据商户查询最近的主题图框
					goodsPic = goodsPicService.getIszhutihuakuang(pc.getCentreId());
				}
				//判断商品有没有勾选主题图框
				if (pc.getIszhutihuakuang() == 1 && goodsPic != null && goodsPic.getPic() != null) {
					pc.setZttkURL(goodsPic.getPic());
				}
				if (productsReqVo.getMid() != null) {
					String s = redisTemplate.opsForValue().get("cardTotal:" + productsReqVo.getMid() + ":" + pc.getId());
					String s1 = s == null ? "0" : s;
					pc.setCartNum(Integer.parseInt(s1));
				}

				Object count = stringRedisTemplate.opsForValue().get("PRODUCT_VIEW_COUNT_" + pc.getId());
				if (count != null) {
					pc.setViewcount((Integer) count);
				}

				//hasoptionsbuy 启用多规格同时下单 hasoption 启用多规格
				if (pc.getHasoption() != null && pc.getHasoption() == 1) {//启用商品多规格
					List<ProductSpecCentre> specList = specCentreMapper.selectByProductId(pc.getId(), 0);
					// 获取规格+规格属性
					if (CollectionUtils.isNotEmpty(specList)) {
						for (ProductSpecCentre spec : specList) {
							List<ProductSpecItemCentre> specItemList = specItemCentreMapper.selectBySpecId(spec.getId(), 0);
							spec.setSpecItemList(specItemList);
						}
						pc.setSpecList(specList);
					}
				}

				//列表中查询规格数据
				pc.setSkus(productSkuCentreMapper.getByProductId(pc.getId()));

				Long pid = pc.getProductId();
				if (pid != null && pid > 0) {
					Product product = productMapper.selectByPrimaryKey(pid);

					pc.setGrandtotal(product.getGrandtotal());
					Integer saleReal = 0;
					Object sale = stringRedisTemplate.opsForValue().get(CACHE_KEY_PRODUCT_SALE.concat(String.valueOf(product.getId())));
					if (sale == null) {
						saleReal = product.getSalesreal();
					} else {
						saleReal = (Integer) sale;
					}
					pc.setSalesreal(saleReal);
					pc.setTotal(product.getTotal());
				} else {
					Object sale = stringRedisTemplate.opsForValue().get(CACHE_KEY_PRODUCT_CENTRE_SALE.concat(pc.getId().toString()));
					if (sale != null) {
						pc.setSalesreal((Integer) sale);
					}
				}

				//查询套餐内商品
				if (productsReqVo.getProductPackageFlag() != null && productsReqVo.getProductPackageFlag() == 1) {
					ProductPackageSku productPackageSku = new ProductPackageSku();
					productPackageSku.setProductCentreId(pc.getId());
					pc.setProductPackageSkuList(productPackageSkuMapper.selectByAll(productPackageSku));
				}
			}
			pageUtils.setRows(list);
		}
		return pageUtils;
	}


	/**
	 * 门店商品列表 前端用
	 *
	 * @param offset
	 * @param limit
	 * @param productsReqVo
	 * @return
	 */
	@Override
	public PageUtils<ProductCentre> getListShopkeeperProducts(int offset, int limit, ProductsReqVo productsReqVo) {
		PageUtils<ProductCentre> pageUtils = new PageUtils<>();
		HashMap<String, Object> map = new HashMap<>(4);
//        Member commander = null;

//        Long teamId = productsReqVo.getTeamId();
//        if (teamId == null) {
//            logger.info("listCentreProducts lose teamId!!");
//            return pageUtils;
//        }
//        commander = memberMapper.selectByPrimaryKey(teamId);
//        if (commander == null) {
//            logger.info("not found commander by teamId:{}", teamId);
//            return pageUtils;
//        }
//        if (productsReqVo.getCentreId() == null) {
//            productsReqVo.setCentreId(commander.getCentreId());
//        }
        /*if (productsReqVo.getIsKuaidi() != null && productsReqVo.getIsKuaidi() == 1) {
            //是快递直发商品
            map.put("isKuaidi", productsReqVo.getIsKuaidi());
        }*/
		map.put("isKuaidi", productsReqVo.getIsKuaidi());
		if (productsReqVo.getCentreId() != null) {
			map.put("centreId", productsReqVo.getCentreId());
		}
		//map.put("teamId", productsReqVo.getTeamId());
//        map.put("teamIdStr", "#" + productsReqVo.getTeamId() + "#");
//        map.put("teamArea", commander.gettCity());
		if (productsReqVo.getIshot() != null) {
			map.put("ishot", productsReqVo.getIshot());
		}
		if (productsReqVo.getIsnew() != null) {
			map.put("isnew", productsReqVo.getIsnew());
		}
		if (productsReqVo.getIsmiaosha() != null) {
			map.put("ismiaosha", productsReqVo.getIsmiaosha());
		}
		if (productsReqVo.getCentreFlag() != null) {
			map.put("centreFlag", productsReqVo.getCentreFlag());
		} else {
			map.put("centreFlag", true);
		}
		if (productsReqVo.getIsvip() != null) {
			map.put("isvip", productsReqVo.getIsvip());
		}
		if (productsReqVo.getCategoryId() != null) {
			map.put("categoryId", productsReqVo.getCategoryId());
		}
		if (StringUtils.isNotEmpty(productsReqVo.getTitle())) {
			map.put("title", productsReqVo.getTitle());
		}
		if (productsReqVo.getTeamId() != null) {
			map.put("teamId", productsReqVo.getTeamId());
		}
		if (productsReqVo.getLiansuoid() != null && productsReqVo.getLiansuoid() != 0) {
			map.put("liansuoid", productsReqVo.getLiansuoid());
		}
		if (productsReqVo.getIsSpellgroup() != null) {
			map.put("isSpellgroup", productsReqVo.getIsSpellgroup());
		}
		if (productsReqVo.getProductType() != null) {
			map.put("productType", productsReqVo.getProductType());
		}
		//预售
		if (productsReqVo.getIspresell() != null) {
			map.put("ispresell", productsReqVo.getIspresell());
		}
		//状态
		if (productsReqVo.getStatus() != null) {
			map.put("status", productsReqVo.getStatus());
		}
        /*if (productsReqVo.getIsSpellgroup()!=null) {
            map.put("isSpellgroup",productsReqVo.getIsSpellgroup());
        }*/
//        if (commander != null) {
//            if (commander.getIsteam() == 3 && productsReqVo.getIsTeam() != null) {
//                map.put("isTeamBuy", 1);
//            } else {
//                map.put("isTeamBuy", 0);
//            }
//        }
		//排序
		if (StringUtil.isNotEmpty(productsReqVo.getSidx())) {
			if (productsReqVo.getSidx().equals("marketprice")) {//价格排序
				map.put("sidx", "pc.marketprice");
				map.put("order", StringUtil.isNotEmpty(productsReqVo.getOrder()) ? productsReqVo.getOrder() : "desc");
			} else if (productsReqVo.getSidx().equals("salesreal")) {
				map.put("sidx", "pc.salesreal");
				map.put("order", StringUtil.isNotEmpty(productsReqVo.getOrder()) ? productsReqVo.getOrder() : "desc");
			} else if (productsReqVo.getSidx().equals("isnew")) {
				String sidx = "pc.isnew " + (StringUtil.isNotEmpty(productsReqVo.getOrder()) ? productsReqVo.getOrder() : "desc") + ", pc.createtime";
				map.put("sidx", sidx);
				map.put("order", StringUtil.isNotEmpty(productsReqVo.getOrder()) ? productsReqVo.getOrder() : "desc");
			}
		}
		//价格区间筛选
		if (productsReqVo.getMinPrice() != null && productsReqVo.getMinPrice().compareTo(BigDecimal.ZERO) == 1) {
			map.put("minPrice", productsReqVo.getMinPrice());
		}
		if (productsReqVo.getMaxPrice() != null && productsReqVo.getMaxPrice().compareTo(BigDecimal.ZERO) == 1) {
			map.put("maxPrice", productsReqVo.getMaxPrice());
		}
		//积分区间筛选
		if (productsReqVo.getMinScore() != null && productsReqVo.getMinScore().compareTo(BigDecimal.ZERO) == 1) {
			map.put("minScore", productsReqVo.getMinScore());
		}
		if (productsReqVo.getMaxScore() != null && productsReqVo.getMaxScore().compareTo(BigDecimal.ZERO) == 1) {
			map.put("maxScore", productsReqVo.getMaxScore());
		}

		GoodsPic goodsPic = null;
		if (productsReqVo.getIsKuaidi() == null) {
			//根据商户查询最近的主题图框
			goodsPic = goodsPicService.getIszhutihuakuang(productsReqVo.getCentreId());
		}
		int total = pCentreMapper.countShopkeeper(map);
		if (total > 0) {
			pageUtils.setTotal(total);
			// List<ProductCentre> list = pCentreMapper.listCentre(map, new RowBounds(offset, limit));
			List<ProductCentre> list = pCentreMapper.getListShopkeeperProducts(map, new RowBounds(offset, limit));
          /* //商品列表
            if(productsReqVo.getCategoryId()== null) {
            	//筛选掉活动专区的商品
            	list = list.stream().filter(ProductCentre ->  ProductCentre.getPcate().longValue()
            			!= 630716 &&  ProductCentre.getPcate().longValue()
            			!= 630759).collect(Collectors.toList());
            }*/
			for (ProductCentre pc : list) {
				if (productsReqVo.getIsKuaidi() != null) {
					//根据商户查询最近的主题图框
					goodsPic = goodsPicService.getIszhutihuakuang(pc.getCentreId());
				}
				//判断商品有没有勾选主题图框
				if (pc.getIszhutihuakuang() == 1 && goodsPic != null && goodsPic.getPic() != null) {
					pc.setZttkURL(goodsPic.getPic());
				}
				if (productsReqVo.getMid() != null) {
					String s = redisTemplate.opsForValue().get("cardTotal:" + productsReqVo.getMid() + ":" + pc.getId());
					String s1 = s == null ? "0" : s;
					pc.setCartNum(Integer.parseInt(s1));
				}

				Object count = stringRedisTemplate.opsForValue().get("PRODUCT_VIEW_COUNT_" + pc.getId());
				if (count != null) {
					pc.setViewcount((Integer) count);
				}

				//hasoptionsbuy 启用多规格同时下单 hasoption 启用多规格
				if (pc.getHasoption() != null && pc.getHasoption() == 1) {//启用商品多规格
					List<ProductSpecCentre> specList = specCentreMapper.selectByProductId(pc.getId(), 0);
					// 获取规格+规格属性
					if (CollectionUtils.isNotEmpty(specList)) {
						for (ProductSpecCentre spec : specList) {
							List<ProductSpecItemCentre> specItemList = specItemCentreMapper.selectBySpecId(spec.getId(), 0);
							spec.setSpecItemList(specItemList);
						}
						pc.setSpecList(specList);
					}
				}

				//列表中查询规格数据
				pc.setSkus(productSkuCentreMapper.getByProductId(pc.getId()));

				Long pid = pc.getProductId();
				if (pid != null && pid > 0) {
					Product product = productMapper.selectByPrimaryKey(pid);

					pc.setGrandtotal(product.getGrandtotal());
					Integer saleReal = 0;
					Object sale = stringRedisTemplate.opsForValue().get(CACHE_KEY_PRODUCT_SALE.concat(String.valueOf(product.getId())));
					if (sale == null) {
						saleReal = product.getSalesreal();
					} else {
						saleReal = (Integer) sale;
					}
					pc.setSalesreal(saleReal);
					pc.setTotal(product.getTotal());
				} else {
					Object sale = stringRedisTemplate.opsForValue().get(CACHE_KEY_PRODUCT_CENTRE_SALE.concat(pc.getId().toString()));
					if (sale != null) {
						pc.setSalesreal((Integer) sale);
					}
				}
			}
			pageUtils.setRows(list);
		}
		return pageUtils;
	}

	/**
	 * 得到商品利润表
	 */
	public PageUtils<ProductCentreCostVo> getProductCentreCostVo(int offset, int limit, ProductsReqVo productsReqVo) {
		PageUtils<ProductCentreCostVo> pageUtils = new PageUtils<ProductCentreCostVo>();
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("strDt", productsReqVo.getStrDt());
		map.put("endDt", productsReqVo.getEndDt());
		map.put("title", productsReqVo.getTitle());
		map.put("supid", productsReqVo.getSupid());
		map.put("centreId", productsReqVo.getCentreId());
		map.put("liansuoid", productsReqVo.getLiansuoid());
		//得到商品利润表
		List<ProductCentreCostVo> list = pCentreMapper.getProductCentreCostVo(map, new RowBounds(offset, limit));
		BigDecimal placostprice = null;
		BigDecimal plapricetotal = null;
		BigDecimal plasalespro = null;
		if (pCentreMapper.getPlacostprice(map) != null) {
			placostprice = new BigDecimal(pCentreMapper.getPlacostprice(map));//平台总成本
		}
		if (pCentreMapper.getPlapricetotal(map) != null) {
			plapricetotal = new BigDecimal(pCentreMapper.getPlapricetotal(map));//平台销售总额
		}
		if (placostprice != null && plapricetotal != null) {
			plasalespro = new BigDecimal(plapricetotal.subtract(placostprice).toString());//平台销售利润
		}

		for (ProductCentreCostVo productCentreCostVo : list) {
			map.put("productId", productCentreCostVo.getProductId());
			ProductCentreCostVo vo = pCentreMapper.getProductCentreById(map);
			if (vo == null) {

			} else {
				productCentreCostVo.setGrandtotal(vo.getGrandtotal());
				productCentreCostVo.setPricetotal(vo.getPricetotal());
				productCentreCostVo.setProductpro(vo.getProductpro());
			}
		}
		for (ProductCentreCostVo productCentreCostVo : list) {
			//添加平台总成本
			if (placostprice != null) {
				productCentreCostVo.setPlacostprice(placostprice.toString());
			}
			//添加平台销售总额
			if (plapricetotal != null) {
				productCentreCostVo.setPlapricetotal(plapricetotal.toString());
			}
			//设置销售比率
			if (productCentreCostVo.getPricetotal() != null && plapricetotal != null) {
				productCentreCostVo.setSalesrat(new BigDecimal(productCentreCostVo.getPricetotal()).divide(plapricetotal, 5, RoundingMode.HALF_UP).toString());
			}
			if (plasalespro != null) {
				productCentreCostVo.setPlasalespro(plasalespro.toString());//平台销售利润
			}
			//设置平台利润率
			if (plasalespro != null && plapricetotal != null) {
				productCentreCostVo.setPlapromar(plasalespro.divide(plapricetotal, 5, RoundingMode.HALF_UP).toString());
			}

			//设置单品利润率
			if (productCentreCostVo.getProductpro() != null && productCentreCostVo.getPricetotal() != null) {
				productCentreCostVo.setProductpromar((new BigDecimal(productCentreCostVo.getProductpro()).divide(new BigDecimal(productCentreCostVo.getPricetotal()), 5, RoundingMode.HALF_UP)).toString());
			}
			//设置单品利润占比
			if (productCentreCostVo.getProductpro() != null && plasalespro != null) {
				productCentreCostVo.setProductpor(new BigDecimal(productCentreCostVo.getProductpro()).divide(plasalespro, 5, RoundingMode.HALF_UP).toString());
			}

		}
		if (list.size() != 0) {
			pageUtils.setTotal(pCentreMapper.gettotal(map).size());
			pageUtils.setRows(list);
		}
		return pageUtils;
	}

	;

	@Override
	public PageUtils<ProductCentre> listByTitleAndId(Long id, String title, Long centreId, Long teamId, int offset, int limit) {
		PageUtils<ProductCentre> pageUtils = new PageUtils<>();
		HashMap<String, Object> params = new HashMap<>(4);
		if (id != null) {
			params.put("id", id);
		}
		if (StringUtils.isNotEmpty(title)) {
			params.put("title", title);
		}
		if (centreId != null) {
			params.put("centreId", centreId);
		}
		if (teamId != null && teamId != 0) {
			params.put("liansuoid", teamId);
		}
		int total = pCentreMapper.countByWhere(params);
		if (total > 0) {
			pageUtils.setTotal(total);
			pageUtils.setRows(pCentreMapper.getListByWhere(params, new RowBounds(offset, limit)));
		}
		return pageUtils;
	}


	/**
	 * 商品名称搜索商品多个商户
	 *
	 * @param id
	 * @param title
	 * @param centreId
	 * @param offset
	 * @param limit
	 * @return
	 */
	public PageUtils<ProductCentre> listByTitleAndCentreId(Long id, String title, List<String> centreId, int offset, int limit) {
		PageUtils<ProductCentre> pageUtils = new PageUtils<>();
		HashMap<String, Object> params = new HashMap<>(4);
		if (id != null) {
			params.put("id", id);
		}
		if (StringUtils.isNotEmpty(title)) {
			params.put("title", title);
		}
		if (centreId != null && centreId.size() > 0) {
			params.put("centreId", centreId);
		}
		int total = pCentreMapper.countByCentreId(params);
		if (total > 0) {
			pageUtils.setTotal(total);
			pageUtils.setRows(pCentreMapper.getListByCentreId(params, new RowBounds(offset, limit)));
		}
		return pageUtils;
	}

	;

	@Override
	public ProductCentre getProductDetail(Long pcId) {
		if (pcId == null) {
			logger.info("centre productId is null");
			return null;
		}
		ProductCentre pc = pCentreMapper.getByKey(pcId);
		if (pc == null) {
			logger.info("not found product info  by pcId :{}", pcId);
			return null;
		}

		if (pc.getProductId() != null) {
			Object sale = stringRedisTemplate.opsForValue().get(CACHE_KEY_PRODUCT_SALE.concat(pc.getProductId().toString()));
			if (sale != null) {
				pc.setSalesreal((Integer) sale);
			} else {
				Product product = productMapper.selectByPrimaryKey(pc.getProductId());
				if (product != null) {
					pc.setSalesreal(product.getSalesreal());
				}
			}
		} else {
			Object sale = stringRedisTemplate.opsForValue().get(CACHE_KEY_PRODUCT_CENTRE_SALE.concat(pcId.toString()));
			if (sale != null) {
				pc.setSalesreal((Integer) sale);
			}
		}
		//关注+1
		pc.setViewcount((int) localRedis.increamNum("PRODUCT_VIEW_COUNT_" + pcId, 1));
		pc.setProductSpecList(specCentreMapper.getByProductId(pc.getId(), 0));
		pc.setSkus(productSkuCentreMapper.getByProductId(pcId));
		//平台商品显示所有购买记录
		if (pc.getProductId() != null) {
			pc.setBuyLogs(orderProductMapper.getProductsBuyLogsBybaseId(pc.getProductId()));
		} else {
			//商户商品只显示自己得·购买记录
			pc.setBuyLogs(orderProductMapper.getProductsBuyLogs(pcId));
		}
		pc.setRecommends(recommendMapper.getProductRecommendList(pcId));

		//hasoptionsbuy 启用多规格同时下单 hasoption 启用多规格
		if (pc.getHasoption() != null && pc.getHasoption() == 1) {//启用商品多规格
			List<ProductSpecCentre> specList = specCentreMapper.selectByProductId(pc.getId(), 0);
			// 获取规格+规格属性
			if (CollectionUtils.isNotEmpty(specList)) {
				for (ProductSpecCentre spec : specList) {
					List<ProductSpecItemCentre> specItemList = specItemCentreMapper.selectBySpecId(spec.getId(), 0);
					spec.setSpecItemList(specItemList);
				}
				pc.setSpecList(specList);
			}
		}

		//列表中查询规格数据
		pc.setSkus(productSkuCentreMapper.getByProductId(pc.getId()));
		return pc;
	}

	@Override
	public int getProductInCartNum(Long mid, Long productId) {
		return memberCartMapper.getProductInCartNum(mid, productId);
	}

	@Override
	public String getProductShareUrl(Long mid, Long productId, String detailUrl, String teamId) throws FileNotFoundException {
		if (productId == null || StringUtils.isEmpty(detailUrl)) {
			logger.info("get product share url not success! lose product or detail url!");
			return null;
		}
		if (teamId == null || teamId.equals("")) {
			teamId = mid.toString();
		} else {
			if (mid != null) {
				if (!teamId.equals(mid.toString())) {
					teamId = mid.toString();
				}
			}
		}
		Member member = memberMapper.selectByPrimaryKey(Long.parseLong(teamId));
		if (member == null) {
			logger.info("member is null!");
			return null;
		}
		// ProductShare share = productShareService.getShareInfo(mid, productId);
		/**已存在分享记录，直接返回**/
        /*if (share != null) {
            logger.info("found share info in db!");
            return share.getSharePic();
        }*/

		Object share = stringRedisTemplate.opsForValue().get("qrurl" + teamId + productId);
		String qrurl = "";
		if (share != null) {
			//得到缓存对象
			qrurl = stringRedisTemplate.opsForValue().get("qrurl" + teamId + productId).toString();
		}


		ProductCentre pc = pCentreMapper.getByKey(productId);
        
      /*  ProductCentre pc = pCentreMapper.getByKey(productId);
        if (pc == null) {
            logger.info("not found product info by id:{}", productId);
            return null;
        }*/
		//商品标签集合热
		List<String> labelList = new ArrayList<String>();
//        if (pc.getIszhicai() != 0) {
//            labelList.add("[直采]");
//        }
		if (pc.getIsmao() != 0) {
			labelList.add("[特卖]");
		}
//        if (pc.getIsfanchang() != 0) {
//            labelList.add("[返场]");
//        }
//        if (pc.getIszhutihuakuang() != 0) {
//            labelList.add("[主题画框]");
//        }
		if (pc.getIsnew() != 0) {
			labelList.add("[新品]");
		}
//        if (pc.getIsbig() != 0) {
//            labelList.add("[大件]");
//        }
//        if (pc.getIslimited() != 0) {
//            labelList.add("[限量]");
//        }
//        if (pc.getIsmiaosha() != 0) {
//            labelList.add("[秒杀]");
//        }
//        if (pc.getIsvip() != 0) {
//            labelList.add("[vip]");
//        }
		if (pc.getIshot() != 0) {
			labelList.add("[爆款]");
		}
//        if (pc.getIspresell() != 0) {
//            labelList.add("[预售]");
//        }
		/**获取二维码文件**/
       /* File file = ImageUtils.createQrFile(detailUrl, 200, 200);
        if (file == null) {
            logger.info("create qr file failed!");
            return null;
        }
        FileInputStream fis = new FileInputStream(file);
        String qrUrl = ossService.uploadImg(fis, null);*/
		/**
		 * 获取二维码地址
		 */
		String qrUrl = "";
		/**已存在分享记录**/
		if (qrurl != null && !qrurl.equals("")) {
			qrUrl = qrurl;
		} else {
			/**
			 * 获取二维码地址
			 */
			qrUrl = getminiqrQr(detailUrl, 200, pc, Long.parseLong(teamId), member.getCentreId());
			if (StringUtils.isEmpty(qrUrl)) {
				logger.info("upload qr file to oss failed!");
				return null;
			}
			localRedis.set("qrurl" + teamId + productId, qrUrl);
		}
        /*String qrUrl = "";
        if(share!=null) {
        	qrUrl = share.getDetailUrl();
        }else {
        	qrUrl = getminiqrQr(detailUrl,200,pc,teamId);
            if (StringUtils.isEmpty(qrUrl)) {
                logger.info("upload qr file to oss failed!");
                return null;
            }
        }*/

		String num = "";
		if (stringRedisTemplate.opsForValue().get("PRODUCT_VIEW_COUNT_" + pc.getId()) != null && !stringRedisTemplate.opsForValue().get("PRODUCT_VIEW_COUNT_" + pc.getId()).equals("")) {
			num = stringRedisTemplate.opsForValue().get("PRODUCT_VIEW_COUNT_" + pc.getId()) + "";
		} else {
			num = "0";
		}

		//SimpleDateFormat sdf = new SimpleDateFormat("MM月dd日HH点mm分");
		InputStream is = ImageUtils.overlapImage(pc.getTitle(), pc.getProductprice().doubleValue(), pc.getMarketprice().doubleValue()
				, pc.getThumbSquare(), qrUrl, "已有" + num + "人关注",
				pc.getUnit(), pc.getVipprice(), labelList, pc.getThumb());
		if (is == null) {
			logger.info("error InputStream is null");
			return null;
		}
		String key = ossService.uploadImg(is, null);
		logger.info("share pic url:{}", key);
        /*if(share==null) {
        	share = new ProductShare();
            share.setDetailUrl(qrUrl);
            share.setMid(mid);
            share.setProductId(productId);
            share.setSharePic(key);
            productShareService.saveShareInfo(share);
        }*/
		return key;
	}

	@Override
	public ProductCentre getByKey(Long id) {
		if (id == null) {
			return null;
		}
		ProductCentre product = pCentreMapper.selectByPrimaryKey(id);
		if (product.getPcate() != 0 && product.getPcate() != null) {
			Category category = categoryMapper.selectByPrimaryKey(product.getPcate());
			product.setPcateName(category.getName());
			List<Category> ccategoryList = categoryService.listCategorys(product.getPcate());
			product.setCcategoryList(ccategoryList);

			if (product.getCcate() != 0 && product.getCcate() != null) {
				category = categoryMapper.selectByPrimaryKey(product.getCcate());
				product.setCcateName(category.getName());
			}
		}
		return product;
	}


	@Override
	@CacheEvict(value = {CACHE_NAME, CACHE_SKU_NAME}, allEntries = true)
	@Transactional(rollbackFor = Exception.class)
	public int update(ProductCentreVo obj) {
		if (obj == null) {
			return 0;
		}
		this.checkStore(obj);
		try {
			ProductCentre productCentre = pCentreMapper.selectByPrimaryKey(obj.getId());
			if (productCentre.getProductId() == null) {
				HashMap<String, String> map = new HashMap<>(16);
				// 商户自己新增的商品,首先更新商品基本信息
				List<ProductSkuCentre> skuList = obj.getSkuList();
				//判断时间是否
				if (obj.getUpStartTime() != null) {
					//如果现在的时间小于上架开始时间才可以修改规格库存
					if (new Date().compareTo(obj.getUpStartTime()) == -1) {
						if (CollectionUtils.isNotEmpty(skuList)) {
							Integer totalStock = 0;
							for (ProductSkuCentre sku : skuList) {
								totalStock += sku.getStock() == null ? 0 : sku.getStock();
							}
							obj.setTotal(totalStock);
						}
						if (obj.getIsSpellgroup() == null) {
							obj.setIsSpellgroup(0);
							obj.setSpellgroupnum(0);
						}
					} else {
						if (obj.getIsSpellgroup() != null) {
							obj.setIsSpellgroup(null);
							obj.setSpellgroupnum(null);
						}
					}
				}
				//如果将商品商品立即上架则将实际销售数量更新为0
          /*      if(obj.getIsclear().equals("1")){
                	obj.setSalesreal(0);
                }*/
				if (obj.getPcate() != null) {
					Category category = categoryService.getByKey(obj.getPcate());
					if (category != null) {
						//添加分类显示
						obj.setIsList(category.getIsList());
					}
				}


				if (obj.getLiansuoid() != null && obj.getLiansuoid() != 0) {
					HashMap<String, Object> searchMap = new HashMap<String, Object>();
					searchMap.put("isteam", MemberType.COMMANDER.getCode());
					searchMap.put("id", obj.getLiansuoid());
					searchMap.put("centreId", productCentre.getCentreId());
					//查找门店是否存在
					List<Member> memberList = memberMapper.getListByMemberWhere(searchMap);
					if (CollectionUtils.isNotEmpty(memberList)) {
						obj.setLiansuoid(memberList.get(0).getId());//连锁门店用户id
						obj.setTeamId(memberList.get(0).getId());//连锁门店用户id
						obj.setLsname(memberList.get(0).gettXiaoqu());//名称
					} else {
						logger.error("保存商品出错，信息为：未找到门店");
						return -1;
					}
				} else {
					obj.setLiansuoid(null);//连锁门店用户id
					obj.setLsname(null);//名称
				}

				if (obj.getLiansuoid() != null && obj.getLiansuoid() == 0) {
					obj.setLiansuoid(null);
				}
				if (obj.getCcate() == null) {
					obj.setCcate(0L);
				}

				//处理商品类型
				if (ProductType.Spresell.getType() == obj.getProductType()) {//预售商品
					obj.setIspresell(1);
				} else if (ProductType.Spellgroup.getType() == obj.getProductType()) {//预售商品
					obj.setIsSpellgroup(1);
				} else if (ProductType.Miaosha.getType() == obj.getProductType()) {//秒杀商品
					obj.setIsmiaosha(1);
				} else {
					obj.setIspresell(0);
					obj.setIsSpellgroup(0);
					obj.setIsmiaosha(0);
				}
				//商品属性
				ProductCentreAttribute productCentreAttribute = pCentreMapper.getProductCentreAttributeByPcId(productCentre.getId());
				if (productCentreAttribute == null) {
					productCentreAttribute = new ProductCentreAttribute();
					productCentreAttribute.setPcId(productCentre.getId());
					productCentreAttribute.setPurchaseText(obj.getPurchaseText());
					productCentreAttribute.setPriceText(obj.getPriceText());
					pCentreMapper.insertProductCentreAttribute(productCentreAttribute);
				} else {
					productCentreAttribute.setPurchaseText(obj.getPurchaseText());
					productCentreAttribute.setPriceText(obj.getPriceText());
					pCentreMapper.updateProductCentreAttribute(productCentreAttribute);
				}


				pCentreMapper.updateByPrimaryKeySelective(obj);

				if (obj.getProductPackageFlag() != null && obj.getProductPackageFlag() == 1 && ValidateUtil.isNotEmptyCollection(obj.getPackageSkuList())) {
					//先删除
					productPackageSkuMapper.deleteByProductCentreId(obj.getId());
					for (ProductPackageSku productPackageSku : obj.getPackageSkuList()) {
						productPackageSku.setProductCentreId(obj.getId());
						productPackageSkuMapper.insert(productPackageSku);
					}
				}

				ProductDataVo productDataVo = new ProductDataVo();
				//复制商品信息导入到资料库
				BeanUtils.copyProperties(obj, productDataVo, "id", "marketprice");
				productDataVo.setProductcId(obj.getId());
				//修改资料库
				productDataMapper.updByProductcId(productDataVo);

				if (!obj.getProductType().equals(ProductType.WaiMai.getType()) && obj.getStatus() == 0) {
					productService.delCart(obj.getId(), productCentre.getIsKuaidi());
				}

				// 更新商品规格,先删除，在新增
				List<ProductSpecCentre> specList = obj.getSpecList();
//                specCentreMapper.deleteByProductId(obj.getId()); // 删除
				if (obj.getHasoption() != null && obj.getHasoption() == 1 && ValidateUtil.isNotEmptyCollection(specList)) {
					List<Long> specIdList = new ArrayList<>();
					for (ProductSpecCentre spec : specList) {
						if (spec.getId() != null) {
							specCentreMapper.updateByPrimaryKeySelective(spec);
						} else {
							spec.setProductId(obj.getId());
							specCentreMapper.insertSelective(spec);
						}

						Long specId = spec.getId();
						specIdList.add(specId);

						List<ProductSpecItemCentre> specItemList = spec.getSpecItemList();
						List<Long> specItemIdList = new ArrayList<>();
						for (ProductSpecItemCentre item : specItemList) {
							if (ValidateUtil.isNotEmptyString(item.getSpecItemHiddenId())) {
								ProductSpecItemCentre productSpecItemCentre = null;
								if (item.getId() != null) {
									productSpecItemCentre = specItemCentreMapper.selectByPrimaryKey(item.getId());
								}
								if (productSpecItemCentre != null) {
									item.setSpecId(specId);
									specItemCentreMapper.updateByPrimaryKeySelective(item);
								} else {
									// 保存规格属性
									item.setSpecId(specId);
									specItemCentreMapper.insertSelective(item);
								}
							}
							specItemIdList.add(item.getId());
							map.put(item.getSpecItemHiddenId(), String.valueOf(item.getId())); // 拿到sku关联id和主键id
						}
						//删除不在ID列表里面的记录
						if (ValidateUtil.isNotEmptyCollection(specItemIdList)) {
							specItemCentreMapper.batchRemoveNotInIds(specId, specItemIdList);
						}
					}

					if (ValidateUtil.isNotEmptyCollection(specIdList)) {
						//删除不在ID列表里面的记录
						specCentreMapper.batchRemoveNotInIds(obj.getId(), specIdList);
					}
				} else {
					//将商品规格删除
					List<ProductSpecCentre> list = specCentreMapper.selectByProductId(obj.getId(), 0);
					List<Long> paramList = new ArrayList<>();
					paramList.add(-1L);
					specCentreMapper.batchRemoveNotInIds(obj.getId(), paramList);
					if (ValidateUtil.isNotEmptyCollection(list)) {
						for (ProductSpecCentre productSpec : list) {
							specItemCentreMapper.batchRemoveNotInIds(productSpec.getId(), paramList);
						}
					}
					productSkuCentreMapper.batchRemoveNotInIds(obj.getId(), paramList);
				}

				// 更新sku
//                productSkuCentreMapper.deleteByProductCentreId(obj.getId());
				if (obj.getHasoption() != null && (obj.getHasoption() == 1) && CollectionUtils.isNotEmpty(skuList)) {
					List<Long> skuIdList = new ArrayList<>();
					for (ProductSkuCentre sku : skuList) {
						//						localRedis.evict(CACHE_SKU_NAME.concat(sku.getId().toString()));
						sku.setProductCentreId(obj.getId());
						sku.setCentreId(productCentre.getCentreId());
						String specs = "";
						String specItemHiddenIdStr = sku.getSpecItemHiddenId();
						if (StringUtils.isNotBlank(specItemHiddenIdStr)) {
							String[] s = specItemHiddenIdStr.split("_");
							//Arrays.sort(s);
							int i = 1;
							for (String str : s) {
								if (s.length == i) {
									specs += map.get(str);
									continue;
								}
								specs += map.get(str) + "_";
								i++;
							}
						}
						sku.setSpecs(specs);
						if (sku.getId() != null) {
							productSkuCentreMapper.updateByPrimaryKeySelective(sku);
						} else {
							productSkuCentreMapper.insertSelective(sku);
						}
						skuIdList.add(sku.getId());
					}
					//删除无效sku
					if (ValidateUtil.isNotEmptyCollection(skuIdList)) {
						productSkuCentreMapper.batchRemoveNotInIds(obj.getId(), skuIdList);
					}
				}

			} else {
				// 商品库中选择的商品,更新商品时只能更新下面属性
				ProductCentre product = new ProductCentre(obj.getId(), obj.getDisplayorder(),
						obj.getStatus(), obj.getUpStartTime(), obj.getUpEndTime(), obj.getMarketprice(),
						obj.getVipprice(), obj.getUsermaxbuy(), obj.getIsnew(),
						obj.getIshot(), obj.getIslimited(), obj.getIsmiaosha(),
						obj.getIsvip(), obj.getIsbig(), obj.getIszhicai(),
						obj.getIsmao(), obj.getIsfanchang(), obj.getIsgerida(),
						obj.getIsfashi(), obj.getIszhutihuakuang(), obj.getMaxbuy(),
						obj.getFreeShipping(), obj.getSendprice(), obj.getDispatchid(),
						obj.getIsFxCommission(), obj.getHeadtype(), obj.getHeadcommission(),
						obj.getSuperiortype(), obj.getSuperiorcommission(), obj.getTihuoday(), obj.getAreas(), 0);
				if (obj.getUsertype() != null) {
					product.setUsertype(obj.getUsertype());
				}
				if (obj.getUsercommission() != null) {
					product.setUsercommission(obj.getUsercommission());
				}
				if (obj.getSuperusertype() != null) {
					product.setSuperusertype(obj.getSuperusertype());
				}
				if (obj.getSuperusercommission() != null) {
					product.setSuperusercommission(obj.getSuperusercommission());
				}
				if (obj.getTeamId() != null) {
					product.setTeamId(obj.getTeamId());
				}
				if (obj.getLiansuoid() != null && obj.getLiansuoid() != 0) {
					product.setLiansuoid(obj.getLiansuoid());
				}

				//处理商品类型
				if (obj.getProductType() == null) {
					obj.setProductType(0);//普通商品
				}
				product.setProductType(obj.getProductType());
				if (ProductType.Spresell.getType() == obj.getProductType()) {//预售商品
					product.setIspresell(1);
				} else if (ProductType.Spellgroup.getType() == obj.getProductType()) {//预售商品
					product.setIsSpellgroup(1);
				} else if (ProductType.Miaosha.getType() == obj.getProductType()) {//秒杀商品
					product.setIsmiaosha(1);
				} else {
					product.setIspresell(0);
					product.setIsSpellgroup(0);
					product.setIsmiaosha(0);
				}


				pCentreMapper.updateByPrimaryKeySelective(product);
				//判断时间是否
				if (obj.getUpStartTime() != null) {
					//如果现在的时间小于上架开始时间才可以修改规格
					if (new Date().compareTo(obj.getUpStartTime()) == -1) {
						if (productCentre.getHasoption() == 1) {
							// 该商品启用了多规格同时购买，在更新sku中的价格
							List<ProductSkuCentre> skuList = obj.getSkuList();
							if (CollectionUtils.isNotEmpty(skuList)) {
								for (ProductSkuCentre sku : skuList) {
									ProductSkuCentre skuCentre = new ProductSkuCentre(sku.getId(), sku.getMarketprice());
									if (sku.getHeadcommission() != null) {
										//设置佣金
										skuCentre.setHeadcommission(sku.getHeadcommission());
									}

									productSkuCentreMapper.updateByPrimaryKeySelective(skuCentre);
								}
							}
						}
					}
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
			logger.error("保存商品出错，信息为：{}", e.getMessage());
			return -1;
		}
		return 1;
	}


	@Override
	public int remove(Long id) {
		if (id == null) {
			return 0;
		}
		ProductCentre obj = new ProductCentre();
		obj.setId(id);
		obj.setDeleted(0);
		return pCentreMapper.updateByPrimaryKeySelective(obj);
	}


	/**
	 * 更新库存
	 *
	 * @param id
	 * @return
	 * @author baolingyu
	 * @date 2018年8月28日-上午11:46:32
	 */
	public int updateDisplayorder(Long id, Integer displayorder) {
		if (id == null) {
			return 0;
		}
		ProductCentre obj = new ProductCentre();
		obj.setId(id);
		obj.setDisplayorder(displayorder);
		return pCentreMapper.updateByPrimaryKeySelective(obj);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public int save(List<Long> ids, Long centreId) {
		try {
			for (Long id : ids) {
				HashMap<String, Object> map1 = new HashMap<>();
				map1.put("productId", id);
				map1.put("centreId", centreId);

				// 做更新处理
				int count = pCentreMapper.countByWhere(map1);
				if (count > 0) {
					continue;
				}
				// 新增商品基本信息  t_product_centre表
				Product product = productMapper.selectByPrimaryKey(id);
				ProductCentre productCentre = new ProductCentre();
				BeanUtils.copyProperties(product, productCentre, "id", "marketprice");
				productCentre.setProductId(id); // 关联product_base表id
				productCentre.setCentreId(centreId); // 商户id
				productCentre.setAuditing(1); // 商品库挑选的商品默认审核通过
				productCentre.setCostprice(product.getMarketprice());
				productCentre.setMarketprice(product.getSuggestsaleprice());
				Centre centre = centreService.getByKey(centreId);
				productCentre.setAreas(centre.getSaleAreas());
				productCentre.setIsList(product.getIsList());
				if (centreId.longValue() == 22) {
					productCentre.setSuperiorcommission(product.getSuggestsaleprice().multiply(new BigDecimal(0.01)));
				}
				pCentreMapper.insertSelective(productCentre);


				HashMap<String, String> specsMap = new HashMap<>(); // 用来存储旧的specItem id和新的specItemId
				// 新增spec
				List<ProductSpec> specList = productSpecMapper.selectByProductId(id);
				if (CollectionUtils.isNotEmpty(specList)) {
					for (ProductSpec spec : specList) {
						ProductSpecCentre specCentre = new ProductSpecCentre();
						BeanUtils.copyProperties(spec, specCentre, "id");
						specCentre.setProductId(productCentre.getId());
						specCentreMapper.insertSelective(specCentre);

						// 新增specItem，操作表t_product_spec_item_centre
						List<ProductSpecItem> specItemList = specItemMapper.selectBySpecId(spec.getId());
						for (ProductSpecItem item : specItemList) {
							ProductSpecItemCentre specItemCentre = new ProductSpecItemCentre();
							BeanUtils.copyProperties(item, specItemCentre, "id");
							specItemCentre.setSpecId(specCentre.getId());
							specItemCentreMapper.insertSelective(specItemCentre);
							specsMap.put(item.getId().toString(), specItemCentre.getId().toString());
						}
					}
				}

				// 获取商品库商品的sku属性
				HashMap<String, Object> map = new HashMap<>();
				map.put("productId", id);
				List<ProductSku> skuList = skuMapper.listByWhereDcx(map);
				if (CollectionUtils.isNotEmpty(skuList)) {
					for (ProductSku sku : skuList) {
						ProductSkuCentre skuCentre = new ProductSkuCentre();
						BeanUtils.copyProperties(sku, skuCentre);
						skuCentre.setProductCentreId(productCentre.getId());
						skuCentre.setCentreId(centreId);
						skuCentre.setSkuId(sku.getId());

						// 用新的specItemId代替旧的specItemId
						String specs = sku.getSpecs();
						String centreSpecs = "";
						if (StringUtils.isNotBlank(specs)) {
							String[] specsArray = specs.split("_");
							for (int i = 0; i < specsArray.length; i++) {
								if (i == specsArray.length - 1) {
									centreSpecs += specsMap.get(specsArray[i]);
								} else {
									centreSpecs += specsMap.get(specsArray[i]) + "_";
								}
							}
						}
						skuCentre.setSpecs(centreSpecs);

						productSkuCentreMapper.insertSelective(skuCentre);
					}
				}
			}
		} catch (Exception e) {
			logger.error("copy product is error,the message is {}", e.getMessage());
			return -1;
		}
		return 1;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public int save(List<Long> ids, Long centreId, Long teamId) {
		try {
			for (Long id : ids) {
				HashMap<String, Object> map1 = new HashMap<>();
				map1.put("productId", id);
				map1.put("centreId", centreId);
				map1.put("liansuoid", teamId);

				// 做更新处理
				int count = pCentreMapper.countByWhere(map1);
				if (count > 0) {
					continue;
				}
				// 新增商品基本信息  t_product_centre表
				Product product = productMapper.selectByPrimaryKey(id);
				ProductCentre productCentre = new ProductCentre();
				BeanUtils.copyProperties(product, productCentre, "id", "marketprice");
				productCentre.setProductId(id); // 关联product_base表id
				productCentre.setCentreId(centreId); // 商户id
				productCentre.setAuditing(1); // 商品库挑选的商品默认审核通过
				productCentre.setCostprice(product.getMarketprice());
				productCentre.setMarketprice(product.getSuggestsaleprice());
				Centre centre = centreService.getByKey(centreId);
				productCentre.setAreas(centre.getSaleAreas());
				productCentre.setIsList(product.getIsList());
				productCentre.setLiansuoid(teamId);
				if (centreId.longValue() == 22) {
					productCentre.setSuperiorcommission(product.getSuggestsaleprice().multiply(new BigDecimal(0.01)));
				}
				pCentreMapper.insertSelective(productCentre);


				HashMap<String, String> specsMap = new HashMap<>(); // 用来存储旧的specItem id和新的specItemId
				// 新增spec
				List<ProductSpec> specList = productSpecMapper.selectByProductId(id);
				if (CollectionUtils.isNotEmpty(specList)) {
					for (ProductSpec spec : specList) {
						ProductSpecCentre specCentre = new ProductSpecCentre();
						BeanUtils.copyProperties(spec, specCentre, "id");
						specCentre.setProductId(productCentre.getId());
						specCentreMapper.insertSelective(specCentre);

						// 新增specItem，操作表t_product_spec_item_centre
						List<ProductSpecItem> specItemList = specItemMapper.selectBySpecId(spec.getId());
						for (ProductSpecItem item : specItemList) {
							ProductSpecItemCentre specItemCentre = new ProductSpecItemCentre();
							BeanUtils.copyProperties(item, specItemCentre, "id");
							specItemCentre.setSpecId(specCentre.getId());
							specItemCentreMapper.insertSelective(specItemCentre);
							specsMap.put(item.getId().toString(), specItemCentre.getId().toString());
						}
					}
				}

				// 获取商品库商品的sku属性
				HashMap<String, Object> map = new HashMap<>();
				map.put("productId", id);
				List<ProductSku> skuList = skuMapper.listByWhereDcx(map);
				if (CollectionUtils.isNotEmpty(skuList)) {
					for (ProductSku sku : skuList) {
						ProductSkuCentre skuCentre = new ProductSkuCentre();
						BeanUtils.copyProperties(sku, skuCentre);
						skuCentre.setProductCentreId(productCentre.getId());
						skuCentre.setCentreId(centreId);
						skuCentre.setSkuId(sku.getId());

						// 用新的specItemId代替旧的specItemId
						String specs = sku.getSpecs();
						String centreSpecs = "";
						if (StringUtils.isNotBlank(specs)) {
							String[] specsArray = specs.split("_");
							for (int i = 0; i < specsArray.length; i++) {
								if (i == specsArray.length - 1) {
									centreSpecs += specsMap.get(specsArray[i]);
								} else {
									centreSpecs += specsMap.get(specsArray[i]) + "_";
								}
							}
						}
						skuCentre.setSpecs(centreSpecs);

						productSkuCentreMapper.insertSelective(skuCentre);
					}
				}
			}
		} catch (Exception e) {
			logger.error("copy product is error,the message is {}", e.getMessage());
			return -1;
		}
		return 1;
	}


	@Override
	public PageUtils<ProductCentre> listCentreProducts(int offset, int limit, ProductCentreVo vo, String idOrName) {
		PageUtils<ProductCentre> pageUtils = new PageUtils<>();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		HashMap<String, Object> map = new HashMap<>(8);
//		if (vo.getCentreId() != null) {
		map.put("centreId", vo.getCentreId());
//		}
		if (vo.getStatus() != null) {
			map.put("status", vo.getStatus());
		}
		if (vo.getPcate() != null) {
			map.put("pcate", vo.getPcate());
		}
		if (vo.getCcate() != null) {
			map.put("ccate", vo.getCcate());
		}
		if (vo.getSupplierId() != null) {
			map.put("supplierId", vo.getSupplierId());
		}
		if (vo.getTitle() != null) {
			map.put("title", vo.getTitle());
		}
		if (StringUtils.isNotEmpty(idOrName)) {
			map.put("idOrName", idOrName);
		}
		if (vo.getBaseId() != null) {
			map.put("baseId", vo.getBaseId());
		}
		if (vo.getUpStartTime() != null) {
			map.put("upStartTime", sdf.format(vo.getUpStartTime()));
		}
		if (vo.getUpEndTime() != null) {
			map.put("upEndTime", sdf.format(vo.getUpEndTime()));
		}
		if (vo.getIsKuaidi() != null) {
			map.put("isKuaidi", vo.getIsKuaidi());
		}
//		if (vo.getAuditing() == 0) {
		map.put("auditing", vo.getAuditing());
//		}
		if (vo.getLiansuoid() != null && vo.getLiansuoid() != 0) {
			map.put("liansuoid", vo.getLiansuoid());
		}
		if (vo.getIsSource() != null) {
			map.put("isSource", vo.getIsSource());
		}
		if (vo.getIsSpellgroup() != null) {
			map.put("isSpellgroup", vo.getIsSpellgroup());
		}
		if (vo.getIsmiaosha() != null) {
			map.put("ismiaosha", vo.getIsmiaosha());
		}
		if (vo.getTeamId() != null) {
			map.put("teamId", vo.getTeamId());
		}
		if (vo.getProductType() != null) {
			map.put("productType", vo.getProductType());
		}
		if (vo.getProductTypeFlag() != null) {
			map.put("productTypeFlag", vo.getProductTypeFlag());
		}

		int total = pCentreMapper.countByWhere(map);
		if (total > 0) {
			pageUtils.setTotal(total);
			List<ProductCentre> list = pCentreMapper.getCentreProducts(map, new RowBounds(offset, limit));
			for (ProductCentre pc : list) {
				if (pc.getProductId() != null) {
					Object sale = stringRedisTemplate.opsForValue().get(CACHE_KEY_PRODUCT_SALE.concat(pc.getProductId().toString()));
					if (sale != null) {
						pc.setSalesreal((Integer) sale);
					} else {
						Product product = productMapper.selectByPrimaryKey(pc.getProductId());
						if (product != null) {
							pc.setSalesreal(product.getSalesreal());
						}
					}
				}
			}
			pageUtils.setRows(list);
		}
		return pageUtils;
	}


	@Override
	public List<ProductCentre> getExportProductCentre(ProductCentreVo vo, String idOrName) {
		HashMap<String, Object> map = new HashMap<>(8);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//		if (vo.getCentreId() != null) {
		map.put("centreId", vo.getCentreId());
//		}
		if (vo.getStatus() != null) {
			map.put("status", vo.getStatus());
		}
		if (vo.getPcate() != null) {
			map.put("pcate", vo.getPcate());
		}
		if (vo.getCcate() != null) {
			map.put("ccate", vo.getCcate());
		}
		if (vo.getSupplierId() != null) {
			map.put("supplierId", vo.getSupplierId());
		}
		if (vo.getTitle() != null) {
			map.put("title", vo.getTitle());
		}
		if (StringUtils.isNotEmpty(idOrName)) {
			map.put("idOrName", idOrName);
		}
		if (vo.getBaseId() != null) {
			map.put("baseId", vo.getBaseId());
		}
		if (vo.getUpStartTime() != null) {
			map.put("upStartTime", sdf.format(vo.getUpStartTime()));
		}
		if (vo.getUpEndTime() != null) {
			map.put("upEndTime", sdf.format(vo.getUpEndTime()));
		}
		if (vo.getIsKuaidi() != null) {
			map.put("isKuaidi", vo.getIsKuaidi());
		}
//		if (vo.getAuditing() == 0) {
		map.put("auditing", vo.getAuditing());
//		}
		if (vo.getIsSpellgroup() != null) {
			map.put("isSpellgroup", vo.getIsSpellgroup());
		}
		List<ProductCentre> list = pCentreMapper.getExportProductCentre(map);
		for (ProductCentre pc : list) {
			if (pc.getProductId() != null) {
				Object sale = stringRedisTemplate.opsForValue().get(CACHE_KEY_PRODUCT_SALE.concat(pc.getProductId().toString()));
				if (sale != null) {
					pc.setSalesreal((Integer) sale);
				} else {
					Product product = productMapper.selectByPrimaryKey(pc.getProductId());
					if (product != null) {
						pc.setSalesreal(product.getSalesreal());
					}
				}
			}
		}
		return list;
	}

	@Override
	public ProductCentre getProductCentreToProductId(Long productId) {
		if (productId == null) {
			logger.info("ProductCentre productId is null");
			return null;
		}
		HashMap<String, Object> searchMap = new HashMap<String, Object>();
		searchMap.put("productId", productId);
		List<ProductCentre> list = pCentreMapper.getListByWhere(searchMap);
		if (list != null && list.size() > 0) {
			ProductCentre productCentre = (ProductCentre) list.get(0);
			return productCentre;
		}
		return null;
	}


	@Override
	public ProductCentreVo detail(Long id) {
		ProductCentre product = pCentreMapper.selectByPrimaryKey(id);
		ProductCentreVo vo = new ProductCentreVo();
		BeanUtils.copyProperties(product, vo);
		List<ProductSpecCentre> specList = specCentreMapper.selectByProductId(product.getId(), 0);
		// 获取规格+规格属性
		if (CollectionUtils.isNotEmpty(specList)) {
			for (ProductSpecCentre spec : specList) {
				List<ProductSpecItemCentre> specItemList = specItemCentreMapper.selectBySpecId(spec.getId(), 0);
				spec.setSpecItemList(specItemList);
			}
			vo.setSpecList(specList);
		}

		// 获取sku
		List<ProductSkuCentre> skuList = productSkuCentreMapper.selectByProductId(product.getId(), 0);
		vo.setSkuList(skuList);

		return vo;
	}

	/**
	 * 检查门店是否一致
	 *
	 * @date 2020/12/31 15:13
	 */
	private void checkStore(ProductCentreVo obj) {
		if (ValidateUtil.isNotEmptyCollection(obj.getPackageSkuList())) {
			boolean bol = false;
			for (ProductPackageSku productPackageSku : obj.getPackageSkuList()) {
				ProductCentre productCentre = productCentreMapper.getByKey(productPackageSku.getRefProductCentreId());
				if (!productCentre.getLiansuoid().equals(obj.getLiansuoid())) {
					bol = true;
				}
			}
			if (bol) {
				throw new BDException("套餐内设置的商品门店与套餐选择的门店不一致");
			}
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public int add(ProductCentreVo obj, Long centreId) {
		this.checkStore(obj);

		HashMap<String, String> map = new HashMap<>();

		//商品详情富文本换行问题处理
		if (StringUtils.isNotBlank(obj.getDescription())) {
			obj.setDescription(obj.getDescription().replaceAll("(\r\n|\r|\n|\n\r)", "</p><p>"));
		}

		try {
			List<ProductSkuCentre> skuList = obj.getSkuList();
			if (CollectionUtils.isNotEmpty(skuList)) {
				Integer totalStock = 0;
				for (ProductSkuCentre sku : skuList) {
					totalStock += sku.getStock() == null ? 0 : sku.getStock();
				}
				obj.setTotal(totalStock);
			}
			// 保存商品
			obj.setCentreId(centreId);
			Centre centre = centreService.getByKey(centreId);
			obj.setAuditing(centre.getVerify() == 0 ? 1 : 0);
			if (obj.getIsKuaidi() != null && obj.getIsKuaidi() != 1) {
				obj.setAreas(centre.getSaleAreas());
			}
			if (obj.getIsKuaidi() == null) {
				obj.setAreas(centre.getSaleAreas());
			}
			if (obj.getPcate() != null && obj.getIsList() == null) {
				Category category = categoryService.getByKey(obj.getPcate());
				if (category != null) {
					//添加分类显示
					obj.setIsList(category.getIsList());
				}
			}
			if (obj.getLiansuoid() != null && obj.getLiansuoid() != 0) {
				HashMap<String, Object> searchMap = new HashMap<String, Object>();
				searchMap.put("isteam", MemberType.COMMANDER.getCode());
				searchMap.put("id", obj.getLiansuoid());
				searchMap.put("centreId", centreId);
				//查找门店是否存在
				List<Member> memberList = memberMapper.getListByMemberWhere(searchMap);
				if (CollectionUtils.isNotEmpty(memberList)) {
					obj.setLiansuoid(memberList.get(0).getId());//连锁门店用户id
					obj.setTeamId(memberList.get(0).getId());//连锁门店用户id
					obj.setLsname(memberList.get(0).gettXiaoqu());//名称
				} else {
					logger.error("保存商品出错，信息为：未找到门店");
					return -2;
				}
			} else {
				obj.setLiansuoid(null);
			}
			if (obj.getLiansuoid() != null && obj.getLiansuoid() == 0) {
				obj.setLiansuoid(null);
			}

			//处理商品类型
			if (obj.getProductType() != null) {
				if (ProductType.Spresell.getType() == obj.getProductType()) {//预售商品
					obj.setIspresell(1);
				} else if (ProductType.Spellgroup.getType() == obj.getProductType()) {//预售商品
					obj.setIsSpellgroup(1);
				} else if (ProductType.Miaosha.getType() == obj.getProductType()) {//秒杀商品
					obj.setIsmiaosha(1);
				}
			}

			//多规格
			if (obj.getSpecList() == null || obj.getSpecList().size() == 0) {
				obj.setHasoption(0);
				obj.setHasoptionsbuy(0);
			}

			if (obj.getUnit() == null) {
				obj.setUnit("0");
			}


			pCentreMapper.insertSelective(obj);

			ProductCentreAttribute productCentreAttribute = new ProductCentreAttribute();
			productCentreAttribute.setPcId(obj.getId());
			productCentreAttribute.setPurchaseText(obj.getPurchaseText());
			productCentreAttribute.setPriceText(obj.getPriceText());
			pCentreMapper.insertProductCentreAttribute(productCentreAttribute);

			//套餐单品新增
			if (obj.getProductPackageFlag() != null && obj.getProductPackageFlag() == 1 && ValidateUtil.isNotEmptyCollection(obj.getPackageSkuList())) {
				for (ProductPackageSku productPackageSku : obj.getPackageSkuList()) {
					productPackageSku.setProductCentreId(obj.getId());
					productPackageSkuMapper.insert(productPackageSku);
				}
			}

			Long productId = obj.getId();
			ProductDataVo productDataVo = new ProductDataVo();
			//复制商品信息导入到资料库
			BeanUtils.copyProperties(obj, productDataVo, "id", "marketprice");
			productDataVo.setProductcId(productId);
			if (productDataVo.getUnit() == null) {
				productDataVo.setUnit("0");
			}
			//保存到资料库
			productDataService.save(productDataVo);

			// 保存商品规格
			List<ProductSpecCentre> specList = obj.getSpecList();
			if (CollectionUtils.isNotEmpty(specList)) {
				for (ProductSpecCentre spec : specList) {
					spec.setProductId(productId);
					specCentreMapper.insertSelective(spec);
					Long specId = spec.getId();

					List<ProductSpecItemCentre> specItemList = spec.getSpecItemList();
					for (ProductSpecItemCentre item : specItemList) {
						// 保存规格属性
						item.setSpecId(specId);
						specItemCentreMapper.insertSelective(item);

						map.put(item.getSpecItemHiddenId(), String.valueOf(item.getId())); // 拿到sku关联id和主键id
					}
				}
			}

			// 保存sku
			if (CollectionUtils.isNotEmpty(skuList)) {
				for (ProductSkuCentre sku : skuList) {
					sku.setProductCentreId(productId);
					String specs = "";
					String specItemHiddenIdStr = sku.getSpecItemHiddenId();
					if (StringUtils.isNotBlank(specItemHiddenIdStr)) {
						String[] s = specItemHiddenIdStr.split("_");
						int i = 1;
						for (String str : s) {
							if (s.length == i) {
								specs += map.get(str);
							} else {
								specs += map.get(str) + "_";
							}
							i++;
						}
					}
					sku.setSpecs(specs);
					productSkuCentreMapper.insertSelective(sku);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("保存商品出错，信息为：{}", e.getMessage());
			return -1;
		}
		return 1;
	}

	@Override
	@CacheEvict(value = {CACHE_NAME, CACHE_SKU_NAME}, allEntries = true)
	public int btnUpdate(Long id, String column) {
		ProductCentre productCentre = pCentreMapper.selectByPrimaryKey(id);
		switch (column) {
			case "isnew":
				productCentre.setIsnew(productCentre.getIsnew() == 1 ? 0 : 1);
				break;
			case "isKuaidi":
				productCentre.setIsKuaidi(productCentre.getIsKuaidi() == 1 ? 0 : 1);
				break;
			case "isTeamBuy":
				productCentre.setIsTeamBuy(productCentre.getIsTeamBuy() == 1 ? 0 : 1);
				break;
			case "isbig":
				productCentre.setIsbig(productCentre.getIsbig() == 1 ? 0 : 1);
				break;
			case "ishot":
				productCentre.setIshot(productCentre.getIshot() == 1 ? 0 : 1);
				break;
			case "isrecommand":
				productCentre.setIsrecommand(productCentre.getIsrecommand() == 1 ? 0 : 1);
				break;
			case "isdiscount":
				productCentre.setIsdiscount(productCentre.getIsdiscount() == 1 ? 0 : 1);
				break;
			case "islimited":
				productCentre.setIslimited(productCentre.getIslimited() == 1 ? 0 : 1);
				break;
			case "istime":
				productCentre.setIstime(productCentre.getIstime() == 1 ? 0 : 1);
				break;
			case "ismiaosha":
				productCentre.setIsmiaosha(productCentre.getIsmiaosha() == 1 ? 0 : 1);
				break;
			case "isvip":
				productCentre.setIsvip(productCentre.getIsvip() == 1 ? 0 : 1);
				break;
			case "iszhicai":
				productCentre.setIszhicai(productCentre.getIszhicai() == 1 ? 0 : 1);
				break;
			case "ismao":
				productCentre.setIsmao(productCentre.getIsmao() == 1 ? 0 : 1);
				break;
			case "isfanchang":
				productCentre.setIsfanchang(productCentre.getIsfanchang() == 1 ? 0 : 1);
				break;
			case "isgerida":
				productCentre.setIsgerida(productCentre.getIsgerida() == 1 ? 0 : 1);
				break;
			case "isfashi":
				productCentre.setIsfashi(productCentre.getIsfashi() == 1 ? 0 : 1);
				break;
			case "iszhutihuakuang":
				productCentre.setIszhutihuakuang(productCentre.getIszhutihuakuang() == 1 ? 0 : 1);
				break;
			case "status":
				productCentre.setStatus(productCentre.getStatus() == 1 ? 0 : 1);
				break;
			case "ispresell":
				productCentre.setIspresell(productCentre.getIspresell() == 1 ? 0 : 1);
				break;
			case "audit":
				productCentre.setAuditing(1);
				break;
		}
		//如果下架删除购物车
		if (productCentre.getStatus() == 0) {
			productService.delCart(productCentre.getId(), productCentre.getIsKuaidi());
		}
		return pCentreMapper.updateByPrimaryKeySelective(productCentre);
	}

	@Override
	@CacheEvict(value = CACHE_NAME, allEntries = true)
	public int updateTotal(Long id, Integer total) {
		ProductCentre productCentre = pCentreMapper.selectByPrimaryKey(id);
		// 更新后库存<0,就返回错误
		if (productCentre.getTotal() + total < 0) {
			throw new BDException("库存不能小于0");
		}
		try {
//            if (productCentre.getProductId() == null) {
			// 说明此商品为商户自己新增商品
			productCentre.setTotal(productCentre.getTotal() + total);
			return pCentreMapper.updateByPrimaryKeySelective(productCentre);
//            }
		} catch (Exception e) {
			logger.error("centre updateTotal error, the message is {}", e.getMessage());
			return 0;
		}
//        return 1;
	}

	@Override
	public Map<Long, SalesStockVo> getProductSalesStocks(List<Long> productIds, Long mid) {
		Map<Long, SalesStockVo> map = new HashMap<>(8);
		if (CollectionUtils.isEmpty(productIds)) {
			return null;
		}
		for (Long productId : productIds) {
			if (productId == null) {
				continue;
			}
			ProductCentre pc = this.getByKey(productId);
			if (pc == null) {
				continue;
			}
			SalesStockVo ssv = null;
			if (pc.getProductId() == null || pc.getProductId() == 0) {
				//商户商品
				Integer saleReal = 0;
				Object sale = stringRedisTemplate.opsForValue().get(CACHE_KEY_PRODUCT_CENTRE_SALE.concat(String.valueOf(pc.getId())));
				if (sale == null) {
					saleReal = pc.getSalesreal();
				} else {
					saleReal = (Integer) sale;
				}
				ssv = new SalesStockVo(saleReal, pc.getTotal());
			} else {
				//平台商品
				Product product = productMapper.selectByPrimaryKey(pc.getProductId());
				if (product != null) {
					Integer saleReal = 0;
					Object sale = stringRedisTemplate.opsForValue().get(CACHE_KEY_PRODUCT_SALE.concat(String.valueOf(product.getId())));
					if (sale == null) {
						saleReal = product.getSalesreal();
					} else {
						saleReal = (Integer) sale;
					}
					ssv = new SalesStockVo(saleReal, product.getTotal());
				} else {
					ssv = new SalesStockVo(0, 0);
				}
			}
			String s = redisTemplate.opsForValue().get("cardTotal:" + mid + ":" + productId);
			String s1 = s == null ? "0" : s;
			ssv.setCartNum(Integer.parseInt(s1));
			map.put(productId, ssv);
		}
		return map;
	}

	@Override
	public int batchAudit(List<Long> ids) {
		return pCentreMapper.batchAudit(ids);
	}

	@Override
	@Cacheable(value = CACHE_NAME, keyGenerator = "localKeyGenerator")
	public ProductCentre getByKeyWithCache(Long id) {
		if (id == null) {
			return null;
		}
		return pCentreMapper.getByKey(id);
	}


	@Override
	@Cacheable(value = CACHE_SKU_NAME, keyGenerator = "localKeyGenerator")
	public ProductSkuCentre getSkuByKeyWithCache(Long centreSkuId) {
		if (centreSkuId == null) {
			return null;
		}
		return productSkuCentreMapper.selectByPrimaryKey(centreSkuId);
	}

	@Override
	public ProductSkuCentre getSkuByKey(Long centreSkuId) {
		return productSkuCentreMapper.selectByPrimaryKey(centreSkuId);
	}

	@Override
	public ProductCentre getProductCentre(Long pcId) {
		ProductCentre pc = pCentreMapper.getByKey(pcId);
		return pc;
	}

	@Override
	public int changeStock(int total, ProductCentre pc) {
		return pCentreMapper.changeStock(total, pc.getId(), pc.getVersion());
	}

	@Override
	public int changeStock(int total, Long productId) {
		return pCentreMapper.changeStock(total, productId, null);
	}

	@Override
	public int refundStock(int total, ProductCentre pc) {
		return pCentreMapper.refundStock(total, pc.getId(), pc.getVersion());
	}

	@Override
	public int changeSkuStock(int total, ProductSkuCentre psc) {
		return productSkuCentreMapper.changeStock(total, psc.getId(), psc.getVersion());
	}

	@Override
	public int changeSkuStock(int total, Long skuId) {
		return productSkuCentreMapper.changeStock(total, skuId, null);
	}

	@Override
	public int refundSkuStock(int total, ProductSkuCentre psc) {
		return productSkuCentreMapper.refundSkuStock(total, psc.getId(), psc.getVersion());
	}

	@Override
	public int updateSort(Product product) {
		return pCentreMapper.updateSore(product);
	}

	@Override
	public int changeCentreProductByIdMap(Map<Object, Object> updMap) {
		return pCentreMapper.changeCentreProductByIdMap(updMap);
	}

	/**
	 * 得到商品利润表
	 */
	public List<ProductCentreCostVo> getProductCentreCostVoData(Map<String, Object> map) {
		return pCentreMapper.getProductCentreCostVoData(map);
	}

	;


	/**
	 * 得到平台总成本
	 *
	 * @param map
	 * @return
	 */
	public String getPlacostprice(Map<String, Object> map) {
		return pCentreMapper.getPlacostprice(map);
	}

	;

	/**
	 * 得到平台销售总额
	 *
	 * @param map
	 * @return
	 */
	public String getPlapricetotal(Map<String, Object> map) {
		return pCentreMapper.getPlapricetotal(map);
	}

	;

	/**
	 * 得到contre商品的所有订单
	 *
	 * @param map
	 * @return
	 */
	public ProductCentreCostVo getProductCentreById(Map<String, Object> map) {
		return pCentreMapper.getProductCentreById(map);
	}

	public String getminiqrQr(String text, Integer width, ProductCentre pc, Long teamId, Long centreId) {
		return null;
	}


//	/*
//	 * 获取 小程序二维码图片
//	 *
//	 */
//	public String getminiqrQr(String text, Integer width, ProductCentre pc, Long teamId, Long centreId) {
//		String qrUrl = "";
//		//String accessToken = WxConfigUtil.getToken();
//		String accessToken = "";
//		//得到站点
//		Centre centre = centreService.getByKey(centreId);
//		if (StringUtils.isEmpty(centre.getRelateAccount())) {
//			accessToken = centreTokenService.getCentreAccessToken(0L);
//			logger.info("----平台token");
//		} else {
//			//商户开的小程序
//			accessToken = centreTokenService.getCentreAccessToken(centre.getCentreId());
//			logger.info("----商户token");
//		}
//		PrintWriter printWriter = null;
//		InputStream is = null;
//
//		try {
//			URL url = new URL("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken);
//			//URL url = new URL("https://api.weixin.qq.com/wxa/getwxacode?access_token="+accessToken);
//			HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
//			httpURLConnection.setRequestMethod("POST");// 提交模式
//			// conn.setConnectTimeout(10000);//连接超时 单位毫秒
//			// conn.setReadTimeout(2000);//读取超时 单位毫秒
//			// 发送POST请求必须设置如下两行
//			httpURLConnection.setDoOutput(true);
//			httpURLConnection.setDoInput(true);
//			// 获取URLConnection对象对应的输出流
//			printWriter = new PrintWriter(httpURLConnection.getOutputStream());
//			// 发送请求参数
//			JSONObject paramJson = new JSONObject();
//			//scene传参数 前端页面加载得到参数
//			paramJson.put("scene", pc.getId() + "m" + teamId + "m" + centreId);
//			//paramJson.put("page", text);
//			paramJson.put("width", width);
//			paramJson.put("is_hyaline", true);
//			paramJson.put("auto_color", false);
//			printWriter.write(paramJson.toString());
//			// flush输出流的缓冲
//			printWriter.flush();
//			BufferedImage small = ImageIO.read(httpURLConnection.getInputStream());
//			is = ImageUtils.getImageStream(small);
//			qrUrl = ossService.uploadImg(is, null);
//		} catch (Exception e) {
//			e.printStackTrace();
//		} finally {
//			try {
//				if (printWriter != null) {
//					printWriter.close();
//				}
//				if (is != null) {
//					is.close();
//				}
//			} catch (Exception e) {
//
//				e.printStackTrace();
//			}
//		}
//		return qrUrl;
//
//	}


	@Override
	public int updateGrandTotal(Long id, Integer total) {
		ProductCentre productCentre = pCentreMapper.selectByPrimaryKey(id);
		try {
			if (productCentre.getProductId() == null) {
				// 说明此商品为商户自己新增商品
				productCentre.setGrandtotal(total);
				return pCentreMapper.updateByPrimaryKeySelective(productCentre);
			}
		} catch (Exception e) {
			logger.error("centre updateTotal error, the message is {}", e.getMessage());
			return 0;
		}
		return 1;
	}


	/**
	 * 获取商品分享图片数据
	 *
	 * @param mid       门店ID
	 * @param productId 商品Id
	 * @param detailUrl 商品详情链接，二维码识别信息
	 * @return
	 * @throws FileNotFoundException
	 */
	public ProductShareVo getProductShareData(Long mid, Long productId, String detailUrl, String teamId, Integer productType) throws FileNotFoundException {
		ProductShareVo productShareVo = new ProductShareVo();
		if (productId == null || StringUtils.isEmpty(detailUrl)) {
			logger.info("get product share url not success! lose product or detail url!");
			return null;
		}
		if (teamId == null || teamId.equals("")) {
			teamId = mid.toString();
		} else {
			if (mid != null) {
				if (!teamId.equals(mid.toString())) {
					teamId = mid.toString();
				}
			}
		}
		Member member = memberMapper.selectByPrimaryKey(Long.parseLong(teamId));
		if (member == null) {
			logger.info("member is null!");
			return null;
		}
		Object share = stringRedisTemplate.opsForValue().get("qrurl" + teamId + productId);
		String qrurl = "";
		String base64 = "data:image/jpeg;base64,";
		if (share != null) {
			//得到缓存对象
			qrurl = stringRedisTemplate.opsForValue().get("qrurl" + teamId + productId).toString();
		}


		ProductCentre pc = getByKeyWithCache(productId);


		if (pc == null) {
			logger.info("not found product info by id:{}", productId);
			return null;
		}
		String title = "";
		//商品标签集合热
//        if (pc.getIszhicai() != 0) {
//            title = "[直采]" + title;
//        }
		if (pc.getIsmao() != 0) {
			title = "[特卖]" + title;
		}
//        if (pc.getIsfanchang() != 0) {
//            title = "[返场]" + title;
//        }
//        if (pc.getIszhutihuakuang() != 0) {
//            title = "[主题画框]" + title;
//        }
		if (pc.getIsnew() != 0) {
			title = "[新品]" + title;
		}
//        if (pc.getIsbig() != 0) {
//            title = "[大件]" + title;
//        }
//        if (pc.getIslimited() != 0) {
//            title = "[限量]" + title;
//        }
//        if (pc.getIsmiaosha() != 0) {
//            title = "[秒杀]" + title;
//        }
//        if (pc.getIsvip() != 0) {
//            title = "[vip]" + title;
//        }
		if (pc.getIshot() != 0) {
			title = "[爆款]" + title;
		}
//        if (pc.getIspresell() != 0) {
//            title = "[预售]" + title;
//        }
		/**已存在分享记录**/
		if (qrurl != null && !qrurl.equals("")) {
			//productShareVo.setQrUrl(base64.concat(ImageToBase64ByOnline(qrurl)));
			productShareVo.setQrUrl(qrurl);
		} else {
			/**
			 * 获取小程序二维码地址
			 */
			qrurl = getminiqrQr(detailUrl, 200, pc, Long.parseLong(teamId), member.getCentreId());
        	/*//去公众号
        	 File file = ImageUtils.createQrFile(detailUrl, 200, 200);
             if (file == null) {
                 logger.info("create qr file failed!");
                 return null;
             }
             FileInputStream fis = new FileInputStream(file);
             qrurl = ossService.uploadImg(fis, null);*/
			if (StringUtils.isEmpty(qrurl)) {
				logger.info("upload qr file to oss failed!");
				return null;
			}
			localRedis.setByDay("qrurl" + teamId + productId, qrurl, 7);
			// productShareVo.setQrUrl(base64.concat(ImageToBase64ByOnline(qrurl)));
			productShareVo.setQrUrl(qrurl);
		}
		productShareVo.setMarketprice((pc.getMarketprice().doubleValue()) + "");
		if (null != productType && ProductType.Spellgroup.getType() == productType) {
			MarketingGroup marketingGroup = marketingGroupMapper.getMarketingGroupById(productId);
			if (null != marketingGroup) {
				if (marketingGroup.getType() == 0) {
					productShareVo.setMarketprice(marketingGroup.getGroupPrice().toString());
					pc = getByKeyWithCache(marketingGroup.getProductId());
					title = "[拼团]" + title;
				} else if (marketingGroup.getType() == 1) {
					productShareVo.setMarketprice(marketingGroup.getGroupPrice().toString());
					pc = getByKeyWithCache(marketingGroup.getProductId());
					title = "[盲拼]" + title;
				}
			}
		} else if (null != productType && ProductType.Miaosha.getType() == productType) {
			MarketingSeckill marketingGroup = marketingSeckillMapper.getMarketingSeckillById(productId);
			if (null != marketingGroup) {
				productShareVo.setMarketprice(marketingGroup.getMinPrice().toString());
				pc = getByKeyWithCache(marketingGroup.getProductId());
				title = "[秒杀]" + title;
			}
		}

		productShareVo.setProductprice((pc.getProductprice().doubleValue()) + "");
		productShareVo.setTitle(title.concat(pc.getTitle()));
		if (pc.getThumbSquare() == null || pc.getThumbSquare().equals("")) {
			// productShareVo.setThumbSquare(base64.concat(ImageToBase64ByOnline(pc.getThumb())));
			productShareVo.setThumbSquare(pc.getThumb());
		} else {
			//productShareVo.setThumbSquare(base64.concat(ImageToBase64ByOnline(pc.getThumbSquare())));
			productShareVo.setThumbSquare(pc.getThumbSquare());
		}

		if (stringRedisTemplate.opsForValue().get("PRODUCT_VIEW_COUNT_" + pc.getId()) != null && !stringRedisTemplate.opsForValue().get("PRODUCT_VIEW_COUNT_" + pc.getId()).equals("")) {
			productShareVo.setProducttotal(stringRedisTemplate.opsForValue().get("PRODUCT_VIEW_COUNT_" + pc.getId()) + "");
		} else {
			productShareVo.setProducttotal("0");
		}
		productShareVo.setUnit(pc.getUnit());
		productShareVo.setVipprice(pc.getVipprice().toString());
		//设置分享的背景图
		ShareConfig shareConfig = configService.getShareConfig(null);
		if (null != shareConfig) {
			productShareVo.setProductShareBgUrl(shareConfig.getProductShareBgUrl());
		}
		return productShareVo;
	}

	@Override
	public ProductShareVo getProductShareDataQrCode(Long mid, Long productId, String detailUrl, String teamId, Integer productType) throws FileNotFoundException {
		ProductShareVo productShareVo = new ProductShareVo();
		if (productId == null || StringUtils.isEmpty(detailUrl)) {
			logger.info("get product share url not success! lose product or detail url!");
			return null;
		}
		if (teamId == null || teamId.equals("")) {
			teamId = mid.toString();
		} else {
			if (mid != null) {
				if (!teamId.equals(mid.toString())) {
					teamId = mid.toString();
				}
			}

		}
		Member member = memberMapper.selectByPrimaryKey(Long.parseLong(teamId));
		if (member == null) {
			logger.info("member is null!");
			return null;
		}

		String cacheName = "QrurlGzh";
		String title = "";
		ProductCentre pc = new ProductCentre();
		if (null != productType && ProductType.Spellgroup.getType() == productType) {

			MarketingGroup marketingGroup = marketingGroupMapper.getMarketingGroupById(productId);
			if (null != marketingGroup) {
				if (MarketingGroupTypeEnum.ORDINARY.getCode().equals(marketingGroup.getMarketingGroupType())) {
					cacheName = cacheName.concat("Spellgroup");
					pc = getByKeyWithCache(marketingGroup.getProductId());
					pc.setMarketprice(marketingGroup.getGroupPrice());
				} else {
					cacheName = cacheName.concat("SpellgroupDlb");
					pc.setId(marketingGroup.getId());
					pc.setMarketprice(marketingGroup.getGroupPrice());
					pc.setProductprice(marketingGroup.getGroupPrice());
					pc.setTitle(marketingGroup.getActivityName());
					pc.setThumbSquare(marketingGroup.getThumb());
					pc.setUnit(null);
					pc.setVipprice(marketingGroup.getVipPrice());
				}

				title = "[拼团]" + title;
			}
		} else if (null != productType && ProductType.Miaosha.getType() == productType) {
			cacheName = cacheName.concat("Miaosha");
			MarketingSeckill marketingGroup = marketingSeckillMapper.getMarketingSeckillById(productId);
			if (null != marketingGroup) {
				pc = getByKeyWithCache(marketingGroup.getProductId());
				pc.setMarketprice(marketingGroup.getMinPrice());
				title = "[秒杀]" + title;
			}
		} else {
			pc = getByKeyWithCache(productId);
			if (pc == null) {
				logger.info("not found product info by id:{}", productId);
				return null;
			}
			//商品标签集合热
//        if (pc.getIszhicai() != 0) {
//            title = "[直采]" + title;
//        }
			if (pc.getIsmao() != 0) {
				title = "[特卖]" + title;
			}
//        if (pc.getIsfanchang() != 0) {
//            title = "[返场]" + title;
//        }
//        if (pc.getIszhutihuakuang() != 0) {
//            title = "[主题画框]" + title;
//        }
			if (pc.getIsnew() != 0) {
				title = "[新品]" + title;
			}
//        if (pc.getIsbig() != 0) {
//            title = "[大件]" + title;
//        }
//        if (pc.getIslimited() != 0) {
//            title = "[限量]" + title;
//        }
//        if (pc.getIsmiaosha() != 0) {
//            title = "[秒杀]" + title;
//        }
//        if (pc.getIsvip() != 0) {
//            title = "[vip]" + title;
//        }
			if (pc.getIshot() != 0) {
				title = "[爆款]" + title;
			}
//        if (pc.getIspresell() != 0) {
//            title = "[预售]" + title;
//        }
		}

		Object share = stringRedisTemplate.opsForValue().get(cacheName + teamId + productId);
		String qrurl = "";
		//String base64 = "data:image/jpeg;base64,";
		if (share != null) {
			//得到缓存对象
			qrurl = stringRedisTemplate.opsForValue().get(cacheName + teamId + productId).toString();
		}

		/**已存在分享记录**/
		if (qrurl != null && !qrurl.equals("")) {
			//productShareVo.setQrUrl(base64.concat(ImageToBase64ByOnline(qrurl)));
			productShareVo.setQrUrl(qrurl);
		} else {
			/**
			 * 获取公众号分享二维码
			 */
			detailUrl = detailUrl + "?productCentreId=" + pc.getId() + "&teamId=" + teamId + "&centreId=" + member.getCentreId();
			BufferedImage bufferedImage = QRCodeUtil.getQrCode(detailUrl, 200, 200);
			InputStream is = ImageUtils.getImageStream(bufferedImage);
			qrurl = ossService.uploadImg(is, null);

			if (StringUtils.isEmpty(qrurl)) {
				logger.info("upload qr file to oss failed!");
				return null;
			}
			localRedis.setByDay(cacheName + teamId + productId, qrurl, 7);
			// productShareVo.setQrUrl(base64.concat(ImageToBase64ByOnline(qrurl)));
			productShareVo.setQrUrl(qrurl);
		}
		productShareVo.setMarketprice((pc.getMarketprice().doubleValue()) + "");

		productShareVo.setProductprice((pc.getProductprice().doubleValue()) + "");
		productShareVo.setTitle(title.concat(pc.getTitle()));
		if (pc.getThumbSquare() == null || pc.getThumbSquare().equals("")) {
			// productShareVo.setThumbSquare(base64.concat(ImageToBase64ByOnline(pc.getThumb())));
			productShareVo.setThumbSquare(pc.getThumb());
		} else {
			//productShareVo.setThumbSquare(base64.concat(ImageToBase64ByOnline(pc.getThumbSquare())));
			productShareVo.setThumbSquare(pc.getThumbSquare());
		}

		if (redisTemplate.opsForValue().get("PRODUCT_VIEW_COUNT_" + pc.getId()) != null && !redisTemplate.opsForValue().get("PRODUCT_VIEW_COUNT_" + pc.getId()).equals("")) {
			productShareVo.setProducttotal(stringRedisTemplate.opsForValue().get("PRODUCT_VIEW_COUNT_" + pc.getId()) + "");
		} else {
			productShareVo.setProducttotal("0");
		}
		productShareVo.setUnit(pc.getUnit());
		productShareVo.setVipprice(pc.getVipprice().toString());
		//设置分享的背景图
		ShareConfig shareConfig = configService.getShareConfig(null);
		if (null != shareConfig) {
			productShareVo.setProductShareBgUrl(shareConfig.getProductShareBgUrl());
		}
		return productShareVo;
	}

	/**
	 * 在线图片转换成base64字符串
	 *
	 * @param imgURL 图片线上路径
	 * @return
	 * @author ZHANGJL
	 * @dateTime 2018-02-23 14:43:18
	 */
	public static String ImageToBase64ByOnline(String imgURL) {
		ByteArrayOutputStream data = new ByteArrayOutputStream();
		InputStream is = null;
		byte[] bystr = null;
		try {
			// 创建URL
			URL url = new URL(imgURL);
			byte[] by = new byte[1024];
			// 创建链接
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			conn.setConnectTimeout(5000);
			conn.setRequestProperty("referer", "https://o.rjkj7.com");
			is = conn.getInputStream();
			// 将内容读取内存中
			int len = -1;
			while ((len = is.read(by)) != -1) {
				data.write(by, 0, len);
			}
			//得到Base64encoder加密
			Encoder encoder = Base64.getEncoder();
			bystr = encoder.encode(data.toByteArray());

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (is != null) {
					is.close();
				}
				if (data != null) {
					data.close();
				}
			} catch (Exception e) {

				e.printStackTrace();
			}
		}

		//org.apache.commons.codec.binary.Base64.encodeBase64Chunked(data.getBytes());
		if (null != bystr) {
			return new String(bystr);
		} else {
			return null;
		}
	}


	@Override
	public int batchUpdateSales(List<Long> asList, int sales) {
		//修改平台
		pCentreMapper.batchUpdateSales(asList, sales);
		//修改站点
		return pCentreMapper.batchUpdateCentreSales(asList, sales);
	}


	/**
	 * 复制单品
	 *
	 * @return
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public int copyProductCentre(Long id, String centerId, String teamId, Integer productType) {
		if (StringUtils.isNotEmpty(teamId)) {
			String[] teamStr = teamId.split(",");
			for (int k = 0; k < teamStr.length; k++) {
				this.copyProductCentreDispose(id, null, Long.parseLong(teamStr[k]), productType);
			}
		} else if (StringUtils.isNotEmpty(centerId)) {
			String[] centerStr = centerId.split(",");
			for (int k = 0; k < centerStr.length; k++) {
				this.copyProductCentreDispose(id, Long.parseLong(centerStr[k]), null, productType);
			}
		}
		return 1;
	}

	private void copyProductCentreDispose(Long id, Long centerId, Long teamId, Integer productType) {
		//商品Id
//        Long productId = pCentreMapper.getId() + 1;
		//得到复制的商品
		ProductCentre productCentre = pCentreMapper.getProductCentre(id);
		//商户商品sku
//        List<ProductSkuCentre> centreList = productSkuCentreMapper.getByProductId(id);
		//商户商品spec
//        List<ProductSpecCentre> specList = specCentreMapper.selectByProductId(id);
//        String end = DateUtils.format(DateUtils.getAddDayDate(new Date(), +1), "yyyy-MM-dd") + " 20:00:00";
//        String start = DateUtils.format(new Date(), "yyyy-MM-dd") + " 20:00:00";
		//id清空
//        productCentre.setId(productId);
//        productCentre.setUpStartTime(DateUtils.parseDate(start, "yyyy-MM-dd HH:mm:ss"));
//        productCentre.setUpEndTime(DateUtils.parseDate(end, "yyyy-MM-dd HH:mm:ss"));
//        productCentre.setTotal(null);
		productCentre.setCreatetime(new Date());
		productCentre.setSales(null);
		productCentre.setSalesreal(null);
//        productCentre.setTimestart(DateUtils.parseDate(start, "yyyy-MM-dd HH:mm:ss"));
//        productCentre.setTimeend(DateUtils.parseDate(end, "yyyy-MM-dd HH:mm:ss"));
		productCentre.setDeleted(1);
//        productCentre.setGrandtotal(null);
		productCentre.setManudate(DateUtils.format(new Date(), "yyyy-MM-dd"));
//        productCentre.setHasoption(0);
//        productCentre.setHasoptionsbuy(0);
		if (ValidateUtil.isNotEmptyObjectOrString(productType)) {
			productCentre.setProductType(productType);
		}
		if (centerId != null) {
			productCentre.setCentreId(centerId);
			productCentre.setTeamId(null);
			productCentre.setLiansuoid(null);
		}
		if (teamId != null) {
			productCentre.setTeamId(teamId);
			productCentre.setLiansuoid(teamId);
			Member member = memberMapper.selectByPrimaryKey(teamId);
			productCentre.setLsname(member.gettXiaoqu());
		}
		//添加新商品
		int num = pCentreMapper.insertSelective(productCentre);

		String ids = "";
		List<ProductSpecCentre> specList = specCentreMapper.selectByProductId(id, 0);
		Map<String, String> spec2Map = new HashMap<>();
		Map<String, String> specItem2Map = new HashMap<>();
		if (CollectionUtils.isNotEmpty(specList)) {
//            Long specId = null;
			//添加spec
			for (int i = 0; i < specList.size(); i++) {
				//specItem
				List<ProductSpecItemCentre> specItemList = specItemCentreMapper.selectBySpecId(specList.get(i).getId(), 0);
				ProductSpecCentre spec = new ProductSpecCentre();
				spec = specList.get(i);
				spec.setProductId(productCentre.getId());
//                specId = specCentreMapper.getMaxId() + (i + 1);
//                spec.setId(specId);
				String oldSpecId = spec.getId().toString();
				//添加sku
				specCentreMapper.insertSelective(spec);
				//老spec-新spec对应的map对
				spec2Map.put(oldSpecId, spec.getId().toString());
				if (CollectionUtils.isNotEmpty(specItemList)) {
					ProductSpecItemCentre productSpecItem = null;
//                    Long specItemId = specItemCentreMapper.getMaxId();
					for (int j = 0; j < specItemList.size(); j++) {
						productSpecItem = specItemList.get(j);
						String oldSpecItemId = productSpecItem.getId().toString();
						productSpecItem.setId(null);
//                        specItemId = specItemId + (i + 1);
//                        productSpecItem.setId(specItemId);
//                        productSpecItem.setShow(null);
						productSpecItem.setSpecId(spec.getId());
//                        ids = ids + specItemId + ",";
						//添加specItem
						specItemCentreMapper.insertSelective(productSpecItem);
						//新老specItem的Map对
						specItem2Map.put(oldSpecItemId, productSpecItem.getId().toString());
					}

				}
			}
		}
//        String[] specItemList = ids.split(",");
		//得到多规格

		List<ProductSkuCentre> centreList = productSkuCentreMapper.getByProductId(id);
		if (CollectionUtils.isNotEmpty(centreList)) {
			ProductSkuCentre sku = null;
			//添加sku
			for (int i = 0; i < centreList.size(); i++) {
				sku = centreList.get(i);
				sku.setStock(sku.getStock());
				sku.setSales(null);
				sku.setSalesreal(null);
				sku.setSalesready(null);
				String specs = sku.getSpecs();
				String[] specArray = specs.split("_");
				if (ValidateUtil.isNotEmptyArray(specArray)) {
					String newSpecs = StringConstans.STR_EMPTY;
					for (String specItemId : specArray) {
						String newSpecItemId = specItem2Map.get(specItemId);
						//如果是第一个，则直接拼接，否则，要加下划线
						newSpecs += ValidateUtil.isEmptyString(newSpecs) ? newSpecItemId : "_" + newSpecItemId;
					}
					sku.setSpecs(newSpecs);
				}

				sku.setProductCentreId(productCentre.getId());
				//添加
				productSkuCentreMapper.insertSelective(sku);
			}
		}
	}

	/**
	 * 拔资料库商品
	 *
	 * @param ids
	 * @param centreId
	 * @return
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public int saveByProductDataId(List<ProductCentreVo> ids, Long centreId) {
		try {
			for (ProductCentreVo vo : ids) {
				String end = null;
				String start = null;
				HashMap<String, Object> map1 = new HashMap<>();
				map1.put("productDataId", vo.getId());
				map1.put("centreId", centreId);
               /* if((vo.getIsKuaidi() != null && vo.getIsKuaidi()==1) || (vo.getIsSpellgroup()!=null
                		&& vo.getIsSpellgroup()==1)) {*/
				if (vo.getIsKuaidi() != null && vo.getIsKuaidi() == 1) {
					map1.put("isKuaidi", vo.getIsKuaidi());
				}
				if (vo.getIsSpellgroup() != null && vo.getIsSpellgroup() == 1) {
					map1.put("isSpellgroup", vo.getIsSpellgroup());
				}
				map1.put("upStartTime", vo.getUpStartTime());
				map1.put("upEndTime", vo.getUpEndTime());
				/*}*//*else {
                	 //团购商品
    	                //今天
    	                if(vo.getUpTime()!=null && vo.getUpTime()==1) {
    	                	start = DateUtils.format(DateUtils.getAddDayDate(new Date(), -1), "yyyy-MM-dd") + " 20:00:00";
    	                	end = DateUtils.format(new Date(), "yyyy-MM-dd") + " 20:00:00";
    	                	//明天
    	                }else if (vo.getUpTime()!=null && vo.getUpTime()==2) {
    	                	end = DateUtils.format(DateUtils.getAddDayDate(new Date(), +1), "yyyy-MM-dd") + " 20:00:00";
    	                	start = DateUtils.format(new Date(), "yyyy-MM-dd") + " 20:00:00";
    	                	//后天
    					}else if (vo.getUpTime()!=null && vo.getUpTime()==3) {
    						start = DateUtils.format(DateUtils.getAddDayDate(new Date(), +1), "yyyy-MM-dd") + " 20:00:00";
    						end = DateUtils.format(DateUtils.getAddDayDate(new Date(), +2), "yyyy-MM-dd") + " 20:00:00";
    					}
    	                if(StringUtils.isNotEmpty(start)) {
    	                	//上架时间
    	                	map1.put("upStartTime",start);
    	                }
    	                if(StringUtils.isNotEmpty(end)) {
    	                   //下架时间
    	                	map1.put("upEndTime",end);
    	                }
                }*/
				// 做更新处理
				int count = pCentreMapper.countByWhere(map1);
				if (count > 0) {
					continue;
				}
				//站点信息
				Centre centre = centreService.getByKey(centreId);
				// 新增商品基本信息  t_product_centre表
				ProductData product = productDataMapper.selectByPrimaryKey(vo.getId());
				ProductCentre productCentre = new ProductCentre();
				BeanUtils.copyProperties(product, productCentre, "id", "marketprice", "isTeamBuy", "liansuoid", "lsname", "isSpellgroup", "spellgroupnum",
						"deleted", "maxbuy", "virtual", "salesready", "iscredits", "showsupply", "areas", "grandtotal", "isKuaidi",
						"ismiaosha", "istime", "isvip", "islimited");
				productCentre.setProductDataId(vo.getId()); // 关联product_base表id
				productCentre.setCentreId(centreId); // 商户id
				//productCentre.setAuditing(1); // 商品库挑选的商品默认审核通过
				productCentre.setAuditing(centre.getVerify() == 0 ? 1 : 0);
				//productCentre.setCostprice(product.getMarketprice());
				// productCentre.setMarketprice(product.getSuggestsaleprice());
				//用户自己设置的商品信息
				productCentre.setMarketprice(vo.getMarketprice());
				productCentre.setProductprice(vo.getProductprice() == null ?
						new BigDecimal("0") : vo.getProductprice());
				productCentre.setCostprice(vo.getCostprice() == null ?
						new BigDecimal("0") : vo.getCostprice());
				productCentre.setTotal(vo.getTotal());
				productCentre.setDisplayorder(vo.getDisplayorder());
                /*productCentre.setTimestart(vo.getTimestart());
                productCentre.setTimeend(vo.getTimeend());*/
				productCentre.setHeadcommission(vo.getHeadcommission() == null ?
						new BigDecimal("0") : vo.getHeadcommission());
				productCentre.setSuperiorcommission(vo.getSuperiorcommission() == null ?
						new BigDecimal("0") : vo.getSuperiorcommission());
				productCentre.setUsertype(0);//用户推荐佣金类型
				productCentre.setUsercommission(vo.getUsercommission() == null ?
						new BigDecimal("0") : vo.getUsercommission());//用户推荐佣金
				productCentre.setSuperusertype(0);//用户推荐人上级佣金类型
				productCentre.setSuperusercommission(vo.getSuperusercommission() == null ?
						new BigDecimal("0") : vo.getSuperusercommission());//用户推荐人上级佣金
				//productCentre.setSuperiortype(vo.getSuperiortype());
				//供应商
				if (vo.getSupplierId() != null) {
					productCentre.setSupplierId(vo.getSupplierId());
				}
               /* //团购商品
                if((vo.getIsKuaidi() == null ||  vo.getIsKuaidi() == 0)
                		&& (vo.getIsSpellgroup()==null || vo.getIsSpellgroup()==0)) {*/
	               /* //今天
	                if(vo.getUpTime()!=null && vo.getUpTime()==1) {
	                	start = DateUtils.format(DateUtils.getAddDayDate(new Date(), -1), "yyyy-MM-dd") + " 20:00:00";
	                	end = DateUtils.format(new Date(), "yyyy-MM-dd") + " 20:00:00";
	                	//明天
	                }else if (vo.getUpTime()!=null && vo.getUpTime()==2) {
	                	end = DateUtils.format(DateUtils.getAddDayDate(new Date(), +1), "yyyy-MM-dd") + " 20:00:00";
	                	start = DateUtils.format(new Date(), "yyyy-MM-dd") + " 20:00:00";
	                	//后天
					}else if (vo.getUpTime()!=null && vo.getUpTime()==3) {
						start = DateUtils.format(DateUtils.getAddDayDate(new Date(), +1), "yyyy-MM-dd") + " 20:00:00";
						end = DateUtils.format(DateUtils.getAddDayDate(new Date(), +2), "yyyy-MM-dd") + " 20:00:00";
					}*/
	               /* if(StringUtils.isNotEmpty(start)) {
	                	//上架时间
	                	 productCentre.setUpStartTime(DateUtils.parseDate(start,"yyyy-MM-dd HH:mm:ss"));
	                	 productCentre.setTimestart(DateUtils.parseDate(start,"yyyy-MM-dd HH:mm:ss"));
	                }
	                if(StringUtils.isNotEmpty(end)) {
	                   //下架时间
	                  productCentre.setUpEndTime(DateUtils.parseDate(end,"yyyy-MM-dd HH:mm:ss"));
	                  productCentre.setTimeend(DateUtils.parseDate(end,"yyyy-MM-dd HH:mm:ss"));
	                }
                }else {*/
				productCentre.setUpStartTime(vo.getUpStartTime());
				productCentre.setUpEndTime(vo.getUpEndTime());
				productCentre.setTimestart(vo.getUpStartTime());
				productCentre.setTimeend(vo.getUpEndTime());
				if (vo.getIsKuaidi() != null && vo.getIsKuaidi() == 1) {
					productCentre.setIsKuaidi(vo.getIsKuaidi());
				}
				if (vo.getIsSpellgroup() != null && vo.getIsSpellgroup() == 1) {
					productCentre.setIsSpellgroup(vo.getIsSpellgroup());
					productCentre.setSpellgroupnum(vo.getSpellgroupnum());
				}
				/*   }*/
				productCentre.setIshot(1);
				productCentre.setIsnew(1);
				productCentre.setIsrecommand(1);
				productCentre.setStatus(2);
				productCentre.setTitle(vo.getTitle());//商品名称
				productCentre.setAreas(centre.getSaleAreas());
				productCentre.setIsList(product.getIsList());
				productCentre.setPcate(product.getPcate());//一级分类
				productCentre.setCcate(product.getCcate());//二级分类
				//验证门店是否存在
				if (vo.getLiansuoid() != null && vo.getLiansuoid() != 0) {
					HashMap<String, Object> searchMap = new HashMap<String, Object>();
					searchMap.put("isteam", MemberType.COMMANDER.getCode());
					searchMap.put("id", vo.getLiansuoid());
					searchMap.put("centreId", centreId);
					//查找门店是否存在
					List<Member> memberList = memberMapper.getListByMemberWhere(searchMap);
					if (CollectionUtils.isNotEmpty(memberList)) {
						productCentre.setLiansuoid(memberList.get(0).getId());
						productCentre.setLsname(memberList.get(0).gettXiaoqu());
					} else {
						return -2;
					}
				}
				pCentreMapper.insertSelective(productCentre);


				HashMap<String, String> specsMap = new HashMap<>(); // 用来存储旧的specItem id和新的specItemId
				// 新增spec
				List<ProductDataSpec> specList = productDataSpecMapper.selectByProductId(vo.getId());
				if (CollectionUtils.isNotEmpty(specList)) {
					for (ProductDataSpec spec : specList) {
						ProductSpecCentre specCentre = new ProductSpecCentre();
						BeanUtils.copyProperties(spec, specCentre, "id");
						specCentre.setProductId(productCentre.getId());
						specCentreMapper.insertSelective(specCentre);

						// 新增specItem，操作表t_product_spec_item_centre
						List<ProductDataSpecItem> specItemList = dataSpecItemMapper.selectBySpecId(spec.getId());
						for (ProductDataSpecItem item : specItemList) {
							ProductSpecItemCentre specItemCentre = new ProductSpecItemCentre();
							BeanUtils.copyProperties(item, specItemCentre, "id");
							specItemCentre.setSpecId(specCentre.getId());
							specItemCentreMapper.insertSelective(specItemCentre);
							specsMap.put(item.getId().toString(), specItemCentre.getId().toString());
						}
					}
				}

				// 获取商品库商品的sku属性
				HashMap<String, Object> map = new HashMap<>();
				map.put("productId", vo.getId());
				List<ProductDataSku> skuList = dataSkuMapper.listByWhereDcx(map);
				if (CollectionUtils.isNotEmpty(skuList)) {
					for (ProductDataSku sku : skuList) {
						ProductSkuCentre skuCentre = new ProductSkuCentre();
						BeanUtils.copyProperties(sku, skuCentre);
						skuCentre.setProductCentreId(productCentre.getId());
						skuCentre.setCentreId(centreId);
						skuCentre.setSkuId(sku.getId());

						// 用新的specItemId代替旧的specItemId
						String specs = sku.getSpecs();
						String centreSpecs = "";
						if (StringUtils.isNotBlank(specs)) {
							String[] specsArray = specs.split("_");
							for (int i = 0; i < specsArray.length; i++) {
								if (i == specsArray.length - 1) {
									centreSpecs += specsMap.get(specsArray[i]);
								} else {
									centreSpecs += specsMap.get(specsArray[i]) + "_";
								}
							}
						}
						skuCentre.setSpecs(centreSpecs);

						productSkuCentreMapper.insertSelective(skuCentre);
					}
				}
			}
		} catch (Exception e) {
			logger.error("copy product is error,the message is {}", e.getMessage());
			return -1;
		}
		return 1;
	}

	@Override
	public String getAppQrcode(QrCodeVo vo) {
		return null;
	}

//	/*
//	 * 获取 小程序二维码图片
//	 *
//	 */
//	@Override
//	public String getAppQrcode(QrCodeVo vo) {
//		logger.info("---进入获取二维码" + JSONObject.toJSONString(vo));
//		String qrUrl = "";
//		Object redisQrUrl = stringRedisTemplate.opsForValue().get("inviteqrurl" + vo.getFlag() + vo.getUserId());
//		//String accessToken = WxConfigUtil.getToken();
//		String accessToken = "";
//		//邀请门店
//		if (redisQrUrl != null) {
//			//缓存里面有邀请图片直接返回
//			qrUrl = redisQrUrl.toString();
//			logger.info("---二维码村人员缓存直接返回");
//			return qrUrl;
//		}
//		logger.info("---二维码没有缓存");
//		//得到站点
//		Centre centre = centreService.getByKey(vo.getCentreId());
//		if (StringUtils.isEmpty(centre.getRelateAccount())) {
//			accessToken = centreTokenService.getCentreAccessToken(0L);
//			logger.info("----平台token");
//		} else {
//			//商户开的小程序
//			accessToken = centreTokenService.getCentreAccessToken(centre.getCentreId());
//			logger.info("----商户token");
//		}
//		logger.error("----accessToken" + accessToken);
//		PrintWriter printWriter = null;
//		InputStream is = null;
//		try {
//			// 发送请求参数
//			JSONObject paramJson = new JSONObject();
//			String scene = "";
//			if (vo.getTypeFlag() != null && vo.getTypeFlag() == 0) {
//				if (StringUtils.isNotEmpty(vo.getUpShopId())) {
//					scene = scene.concat("sid!").concat(vo.getUpShopId() + "-");
//				}
//				if (vo.getCentreId() != null) {
//					scene = scene.concat("cid!").concat(vo.getCentreId() + "-");
//				}
//			}
//			if (StringUtils.isNotEmpty(vo.getUpCentreId())) {
//				scene = scene.concat("ucid!").concat(vo.getUpCentreId() + "-");
//			}
//			if (ValidateUtil.isNotEmptyString(vo.getUserId())) {
//				Member user = memberMapper.selectByPrimaryKey(Long.parseLong(vo.getUserId()));
//				//店员角色，需要增加参数店员参数
//				if (null != user && user.getIsClerk() == 1) {
//					scene = scene.concat("kd!").concat(vo.getUserId() + "-");
//				}
//			}
//			if (StringUtils.isNotEmpty(vo.getGoodsId())) {
//				scene = scene.concat("gid!").concat(vo.getGoodsId() + "-");
//			}
//			if (StringUtils.isNotEmpty(vo.getCd())) {
//				scene = scene.concat("cd!").concat(vo.getCd() + "-");
//			}
//			if (StringUtils.isNotEmpty(vo.getUserId())) {
//				scene = scene.concat("uid!").concat(vo.getUserId() + "-");
//			}
//			if (vo.getTid() != null) {
//				scene = scene.concat("tid!").concat(vo.getTid() + "-");
//			}
//            /* if(StringUtils.isNotEmpty(vo.getUserNickName())) {
//            	 scene =scene.concat("nm!").concat(vo.getUserNickName()).concat("?");
//             }*/
//			if (StringUtils.isNotEmpty(vo.getSeatNum())) {
//				scene = scene.concat("seatNum!").concat(vo.getSeatNum() + "");
//			}
//			logger.info("----参数" + scene);
//			//scene传参数 前端页面加载得到参数
//			//最大32个可见字符，只支持数字，大小写英文以及部分特殊字符：!#$&'()*+,/:;=?@-._~，
//			// 其它字符请自行编码为合法字符（因不支持%，中文无法使用 urlencode 处理，请使用其他编码方式）
//			paramJson.put("scene", scene);
//			if (StringUtils.isNotEmpty(vo.getUrl())) {
//				paramJson.put("page", vo.getUrl());
//			}
//			paramJson.put("width", 200);
//			paramJson.put("is_hyaline", true);
//			paramJson.put("auto_color", false);
//			logger.error("----小程序二维码获取参数" + JSONObject.toJSONString(paramJson));
//
//			String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken;
//			HttpClient httpClient = new HttpClient();
//			PostMethod postMethod = new PostMethod(url);
//			RequestEntity se = new StringRequestEntity(paramJson.toString() ,"application/json" ,"UTF-8");
//			postMethod.setRequestEntity(se);
//			postMethod.setRequestHeader("Content-Type","application/json");
//			int execute = httpClient.executeMethod(postMethod);
//			System.out.println("execute:" + execute);
//			logger.error("----小程序二维码返回信息" + postMethod.getResponseBodyAsString());
//			BufferedImage small = ImageIO.read(postMethod.getResponseBodyAsStream());
//			logger.error("----小程序二维码" + small);
//			is = ImageUtils.getImageStream(small);
//			qrUrl = ossService.uploadImg(is, null);
//			logger.info("----二维码地址" + qrUrl);
//			if (StringUtils.isNotEmpty(qrUrl)) {
//				//邀请码设置缓存
//				localRedis.set("inviteqrurl" + vo.getFlag() + vo.getUserId(), qrUrl);
//				logger.info("----二维码地址存入缓存");
//			}
//		} catch (Exception e) {
//			e.printStackTrace();
//			logger.info("---获取二维码错误" + e.toString());
//		} finally {
//			try {
//				if (printWriter != null) {
//					printWriter.close();
//				}
//				if (is != null) {
//					is.close();
//				}
//			} catch (Exception e) {
//
//				e.printStackTrace();
//			}
//		}
//		logger.info("---获取二维码地址返回" + qrUrl);
//		return qrUrl;
//
//	}

	@Override
	public List<ProductSkuCentre> getSkuListByProductId(Long productId) {
		return productSkuCentreMapper.getByProductId(productId);
	}

	@Override
	public ProductSkuCentre getSkuBySpecs(String specs) {
		return productSkuCentreMapper.getSkuBySpecs(specs);
	}

	@Override
	public PageUtils<ProductCentre> getCashierProductList(HashMap<String, Object> map, Integer offset, Integer limit) {
		PageUtils<ProductCentre> pageUtils = new PageUtils<>();
		int total = pCentreMapper.countCentre(map);
		if (total > 0) {
			pageUtils.setTotal(total);
			List<ProductCentre> list = pCentreMapper.getListCentreProducts(map, new RowBounds(offset, limit));
			for (ProductCentre pc : list) {
				Object count = stringRedisTemplate.opsForValue().get("PRODUCT_VIEW_COUNT_" + pc.getId());
				if (count != null) {
					pc.setViewcount((Integer) count);
				}
				//hasoptionsbuy 启用多规格同时下单 hasoption 启用多规格
				if (pc.getHasoption() != null && pc.getHasoption() == 1) {//启用商品多规格
					List<ProductSpecCentre> specList = specCentreMapper.selectByProductId(pc.getId(), 0);
					// 获取规格+规格属性
					if (CollectionUtils.isNotEmpty(specList)) {
						for (ProductSpecCentre spec : specList) {
							List<ProductSpecItemCentre> specItemList = specItemCentreMapper.selectBySpecId(spec.getId(), 0);
							spec.setSpecItemList(specItemList);
						}
						pc.setSpecList(specList);
					}
				}

				//列表中查询规格数据
				pc.setSkus(productSkuCentreMapper.getByProductId(pc.getId()));

				Long pid = pc.getProductId();
				if (pid != null && pid > 0) {
					Product product = productMapper.selectByPrimaryKey(pid);

					pc.setGrandtotal(product.getGrandtotal());
					Integer saleReal = 0;
					Object sale = stringRedisTemplate.opsForValue().get(CacheKeyLocal.CACHE_KEY_PRODUCT_SALE.concat(String.valueOf(product.getId())));
					if (sale == null) {
						saleReal = product.getSalesreal();
					} else {
						saleReal = (Integer) sale;
					}
					pc.setSalesreal(saleReal);
					pc.setTotal(product.getTotal());
				} else {
					Object sale = stringRedisTemplate.opsForValue().get(CACHE_KEY_PRODUCT_CENTRE_SALE.concat(pc.getId().toString()));
					if (sale != null) {
						pc.setSalesreal((Integer) sale);
					}
				}

				//查询套餐内商品
				if (pc.getProductPackageFlag() != null && pc.getProductPackageFlag() == 1) {
					ProductPackageSku productPackageSku = new ProductPackageSku();
					productPackageSku.setProductCentreId(pc.getId());
					pc.setProductPackageSkuList(productPackageSkuMapper.selectByAll(productPackageSku));
				}
			}
			pageUtils.setRows(list);
		}
		return pageUtils;
	}


	@Override
	public List<ProductCentre> getAllCentreProductByType(ProductsReqVo productsReqVo) {
		Map map = new HashMap<>();
		Member commander = null;

		Long teamId = productsReqVo.getTeamId();
		if (teamId == null) {
			logger.info("listCentreProducts lose teamId!!");
			throw new BDException("查询门店信息失败！");
		}
		commander = memberMapper.selectByPrimaryKey(teamId);
		if (commander == null) {
			logger.info("not found commander by teamId:{}", teamId);
			throw new BDException("查询门店信息失败");
		}
		if (productsReqVo.getCentreId() == null) {
			productsReqVo.setCentreId(commander.getCentreId());
		}

		map.put("centreId", productsReqVo.getCentreId());
		if (productsReqVo.getCategoryId() != null) {
			map.put("categoryId", productsReqVo.getCategoryId());
		}
		if (StringUtils.isNotEmpty(productsReqVo.getTitle())) {
			map.put("title", productsReqVo.getTitle());
		}
		if (productsReqVo.getLiansuoid() != null && productsReqVo.getLiansuoid() != 0) {
			map.put("liansuoid", productsReqVo.getLiansuoid());
		}
		if (productsReqVo.getProductType() != null) {
			map.put("productType", productsReqVo.getProductType());
		}

		if (productsReqVo.getIsziti() != null) {
			map.put("isziti", productsReqVo.getIsziti());
		}
		if (productsReqVo.getIswaimai() != null) {
			map.put("iswaimai", productsReqVo.getIswaimai());
		}
		if (productsReqVo.getIstangshi() != null) {
			map.put("istangshi", productsReqVo.getIstangshi());
		}
		if (productsReqVo.getProductPackageFlag() != null) {
			map.put("productPackageFlag", productsReqVo.getProductPackageFlag());
		}

		//排序
		if ("marketprice".equals(productsReqVo.getSidx())) {//价格排序
			map.put("sidx", "pc.marketprice");
			map.put("order", StringUtil.isNotEmpty(productsReqVo.getOrder()) ? productsReqVo.getOrder() : "desc");
		} else if ("salesreal".equals(productsReqVo.getSidx())) {
			map.put("sidx", "pc.salesreal");
			map.put("order", StringUtil.isNotEmpty(productsReqVo.getOrder()) ? productsReqVo.getOrder() : "desc");
		} else if ("isnew".equals(productsReqVo.getSidx())) {
			String sidx = "pc.isnew " + (StringUtil.isNotEmpty(productsReqVo.getOrder()) ? productsReqVo.getOrder() : "desc") + ", pc.createtime";
			map.put("sidx", sidx);
			map.put("order", StringUtil.isNotEmpty(productsReqVo.getOrder()) ? productsReqVo.getOrder() : "desc");
		} else {//否则，使用后台排序接口来处理
			map.put("sidx", "pc.displayorder");
			map.put("order", "desc");
		}

		List<ProductCentre> list = pCentreMapper.getListCentreProducts(map);

		for (ProductCentre pc : list) {

			if (productsReqVo.getMid() != null) {
				String s = redisTemplate.opsForValue().get("cardTotal:" + productsReqVo.getMid() + ":" + pc.getId());
				String s1 = s == null ? "0" : s;
				pc.setCartNum(Integer.parseInt(s1));
			}

			Object count = stringRedisTemplate.opsForValue().get("PRODUCT_VIEW_COUNT_" + pc.getId());
			if (count != null) {
				pc.setViewcount((Integer) count);
			}

			//hasoptionsbuy 启用多规格同时下单 hasoption 启用多规格
			if (pc.getHasoption() != null && pc.getHasoption() == 1) {//启用商品多规格
				List<ProductSpecCentre> specList = specCentreMapper.selectByProductId(pc.getId(), 0);
				// 获取规格+规格属性
				if (CollectionUtils.isNotEmpty(specList)) {
					for (ProductSpecCentre spec : specList) {
						List<ProductSpecItemCentre> specItemList = specItemCentreMapper.selectBySpecId(spec.getId(), 0);
						spec.setSpecItemList(specItemList);
					}
					pc.setSpecList(specList);
				}
			}
			//获取SKU
			//pc.setSkus(productSkuCentreMapper.getByProductId(pc.getId()));

			if (productsReqVo.getProductPackageFlag() != null && productsReqVo.getProductPackageFlag() == 1) {
				ProductPackageSku productPackageSku = new ProductPackageSku();
				productPackageSku.setProductCentreId(pc.getId());
				pc.setProductPackageSkuList(productPackageSkuMapper.selectByAll(productPackageSku));
			}
		}

		return list;
	}

	@Override
	public PageUtils<ProductCentre> centreProductByTypePage(ProductsReqVo productsReqVo, Integer offset, Integer limit) {
		HashMap<String, Object> map = new HashMap<>();

//        Long teamId = productsReqVo.getTeamId();
//        if (teamId == null) {
//            logger.info("listCentreProducts lose teamId!!");
//            throw new BDException("查询门店信息失败！");
//        }
//        Member commander = memberMapper.selectByPrimaryKey(teamId);
//        if (commander == null) {
//            logger.info("not found commander by teamId:{}", teamId);
//            throw new BDException("查询门店信息失败");
//        }
//        if (productsReqVo.getCentreId() == null) {
//            productsReqVo.setCentreId(commander.getCentreId());
//        }

		map.put("centreId", productsReqVo.getCentreId());
		if (productsReqVo.getCategoryId() != null) {
			map.put("categoryId", productsReqVo.getCategoryId());
		}
		if (StringUtils.isNotEmpty(productsReqVo.getTitle())) {
			map.put("title", productsReqVo.getTitle());
		}
		if (productsReqVo.getLiansuoid() != null && productsReqVo.getLiansuoid() != 0) {
			map.put("liansuoid", productsReqVo.getLiansuoid());
		}
		if (productsReqVo.getProductType() != null) {
			map.put("productType", productsReqVo.getProductType());
		}

		if (productsReqVo.getIsziti() != null) {
			map.put("isziti", productsReqVo.getIsziti());
		}
		if (productsReqVo.getIswaimai() != null) {
			map.put("iswaimai", productsReqVo.getIswaimai());
		}
		if (productsReqVo.getIstangshi() != null) {
			map.put("istangshi", productsReqVo.getIstangshi());
		}
		//排序
		if ("marketprice".equals(productsReqVo.getSidx())) {//价格排序
			map.put("sidx", "pc.marketprice");
			map.put("order", StringUtil.isNotEmpty(productsReqVo.getOrder()) ? productsReqVo.getOrder() : "desc");
		} else if ("salesreal".equals(productsReqVo.getSidx())) {
			map.put("sidx", "pc.salesreal");
			map.put("order", StringUtil.isNotEmpty(productsReqVo.getOrder()) ? productsReqVo.getOrder() : "desc");
		} else if ("isnew".equals(productsReqVo.getSidx())) {
			String sidx = "pc.isnew " + (StringUtil.isNotEmpty(productsReqVo.getOrder()) ? productsReqVo.getOrder() : "desc") + ", pc.createtime";
			map.put("sidx", sidx);
			map.put("order", StringUtil.isNotEmpty(productsReqVo.getOrder()) ? productsReqVo.getOrder() : "desc");
		} else {//否则，使用后台排序接口来处理
			map.put("sidx", "pc.displayorder");
			map.put("order", "desc");
		}
		PageUtils<ProductCentre> pageUtils = new PageUtils<>();
		int total = pCentreMapper.countCentre(map);
		if (total > 0) {
			pageUtils.setTotal(total);
			List<ProductCentre> list = pCentreMapper.getListCentreProducts(map, new RowBounds(offset, limit));

			for (ProductCentre pc : list) {

				if (productsReqVo.getMid() != null) {
					String s = redisTemplate.opsForValue().get("cardTotal:" + productsReqVo.getMid() + ":" + pc.getId());
					String s1 = s == null ? "0" : s;
					pc.setCartNum(Integer.parseInt(s1));
				}

				Object count = stringRedisTemplate.opsForValue().get("PRODUCT_VIEW_COUNT_" + pc.getId());
				if (count != null) {
					pc.setViewcount((Integer) count);
				}

				//hasoptionsbuy 启用多规格同时下单 hasoption 启用多规格
				if (pc.getHasoption() != null && pc.getHasoption() == 1) {//启用商品多规格
					List<ProductSpecCentre> specList = specCentreMapper.selectByProductId(pc.getId(), 0);
					// 获取规格+规格属性
					if (CollectionUtils.isNotEmpty(specList)) {
						for (ProductSpecCentre spec : specList) {
							List<ProductSpecItemCentre> specItemList = specItemCentreMapper.selectBySpecId(spec.getId(), 0);
							spec.setSpecItemList(specItemList);
						}
						pc.setSpecList(specList);
					}
				}
				//获取SKU
				//pc.setSkus(productSkuCentreMapper.getByProductId(pc.getId()));
			}
			pageUtils.setRows(list);
		}

		return pageUtils;
	}

	@Override
	public int updateProductCenter(ProductCentre productCentre) {
		return productCentreMapper.updateByPrimaryKeySelective(productCentre);
	}

	@Override
	public int updateProductSkuCenter(ProductSkuCentre productSkuCentre) {
		return productSkuCentreMapper.updateByPrimaryKeySelective(productSkuCentre);
	}

	@Override
	public int updateProductCentreStatus(Long id, Integer status) {
		if (id == null) {
			return 0;
		}
		ProductCentre productCentre = new ProductCentre();
		productCentre.setId(id);
		productCentre.setStatus(status);

		return pCentreMapper.updateByPrimaryKeySelective(productCentre);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public int saveProductByData(List<Long> ids, Long centreId, Long liansuoid) {
		try {
			for (Long id : ids) {

				HashMap<String, Object> map1 = new HashMap<>();
				map1.put("productDataId", id);
				map1.put("centreId", centreId);

				//站点信息
				Centre centre = centreService.getByKey(centreId);
				// 新增商品基本信息  t_product_centre表
				ProductData product = productDataMapper.selectByPrimaryKey(id);
				ProductCentre productCentre = new ProductCentre();
				BeanUtils.copyProperties(product, productCentre, "id", "marketprice", "isTeamBuy", "liansuoid", "lsname", "isSpellgroup", "spellgroupnum",
						"deleted", "maxbuy", "virtual", "salesready", "iscredits", "showsupply", "areas", "grandtotal", "isKuaidi",
						"ismiaosha", "istime", "isvip", "islimited");
				productCentre.setProductDataId(product.getId()); // 关联product_base表id
				productCentre.setCentreId(centreId); // 商户id
				productCentre.setLiansuoid(liansuoid);
				//productCentre.setAuditing(1); // 商品库挑选的商品默认审核通过
				productCentre.setAuditing(centre.getVerify() == 0 ? 1 : 0);


				productCentre.setHeadcommission(BigDecimal.ZERO);
				productCentre.setSuperiorcommission(BigDecimal.ZERO);
				productCentre.setUsertype(0);//用户推荐佣金类型
				productCentre.setUsercommission(BigDecimal.ZERO);//用户推荐佣金
				productCentre.setSuperusertype(0);//用户推荐人上级佣金类型
				productCentre.setSuperusercommission(BigDecimal.ZERO);//用户推荐人上级佣金


				/*   }*/
				productCentre.setIshot(1);
				productCentre.setIsnew(1);
				productCentre.setIsrecommand(1);
				productCentre.setStatus(0);
				productCentre.setTitle(product.getTitle());//商品名称
				productCentre.setAreas(centre.getSaleAreas());
				productCentre.setIsList(product.getIsList());
				productCentre.setPcate(product.getPcate());//一级分类
				productCentre.setCcate(product.getCcate());//二级分类
				//验证团长是否存在
//                if (vo.getLiansuoid() != null && vo.getLiansuoid() != 0) {
//                    HashMap<String, Object> searchMap = new HashMap<String, Object>();
//                    searchMap.put("isteam", MemberType.COMMANDER.getCode());
//                    searchMap.put("id", vo.getLiansuoid());
//                    searchMap.put("centreId", centreId);
//                    //查找团长是否存在
//                    List<Member> memberList = memberMapper.getListByMemberWhere(searchMap);
//                    if (CollectionUtils.isNotEmpty(memberList)) {
//                        productCentre.setLiansuoid(memberList.get(0).getId());
//                        productCentre.setLsname(memberList.get(0).getRealname());
//                    } else {
//                        return -2;
//                    }
//                }
				pCentreMapper.insertSelective(productCentre);


				HashMap<String, String> specsMap = new HashMap<>(); // 用来存储旧的specItem id和新的specItemId
				// 新增spec
				List<ProductDataSpec> specList = productDataSpecMapper.selectByProductId(id);
				if (CollectionUtils.isNotEmpty(specList)) {
					for (ProductDataSpec spec : specList) {
						ProductSpecCentre specCentre = new ProductSpecCentre();
						BeanUtils.copyProperties(spec, specCentre, "id");
						specCentre.setProductId(productCentre.getId());
						specCentreMapper.insertSelective(specCentre);

						// 新增specItem，操作表t_product_spec_item_centre
						List<ProductDataSpecItem> specItemList = dataSpecItemMapper.selectBySpecId(spec.getId());
						for (ProductDataSpecItem item : specItemList) {
							ProductSpecItemCentre specItemCentre = new ProductSpecItemCentre();
							BeanUtils.copyProperties(item, specItemCentre, "id");
							specItemCentre.setSpecId(specCentre.getId());
							specItemCentreMapper.insertSelective(specItemCentre);
							specsMap.put(item.getId().toString(), specItemCentre.getId().toString());
						}
					}
				}

				// 获取商品库商品的sku属性
				HashMap<String, Object> map = new HashMap<>();
				map.put("productId", id);
				List<ProductDataSku> skuList = dataSkuMapper.listByWhereDcx(map);
				if (CollectionUtils.isNotEmpty(skuList)) {
					for (ProductDataSku sku : skuList) {
						ProductSkuCentre skuCentre = new ProductSkuCentre();
						BeanUtils.copyProperties(sku, skuCentre);
						skuCentre.setProductCentreId(productCentre.getId());
						skuCentre.setCentreId(centreId);
						skuCentre.setSkuId(sku.getId());

						// 用新的specItemId代替旧的specItemId
						String specs = sku.getSpecs();
						String centreSpecs = "";
						if (StringUtils.isNotBlank(specs)) {
							String[] specsArray = specs.split("_");
							for (int i = 0; i < specsArray.length; i++) {
								if (i == specsArray.length - 1) {
									centreSpecs += specsMap.get(specsArray[i]);
								} else {
									centreSpecs += specsMap.get(specsArray[i]) + "_";
								}
							}
						}
						skuCentre.setSpecs(centreSpecs);

						productSkuCentreMapper.insertSelective(skuCentre);
					}
				}
			}
		} catch (Exception e) {
			logger.error("copy product is error,the message is {}", e.getMessage());
			return -1;
		}
		return 1;
	}

	@Override
	public int getProductCenterSales(Long productId, Long skuId) {
		return 0;
	}

	@Override
	public int insertProductCentreAttribute(ProductCentreAttribute productCentreAttribute) {
		return productCentreMapper.insertProductCentreAttribute(productCentreAttribute);
	}

	@Override
	public int deleteProductCentreAttribute(Long pcId) {
		return productCentreMapper.deleteProductCentreAttribute(pcId);
	}

	@Override
	public int updateProductCentreAttribute(ProductCentreAttribute productCentreAttribute) {
		return productCentreMapper.updateProductCentreAttribute(productCentreAttribute);
	}

	@Override
	public ProductCentreAttribute getProductCentreAttributeByPcId(Long pcId) {
		return productCentreMapper.getProductCentreAttributeByPcId(pcId);
	}
}
